package com.hutao.manage.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hutao.manage.component.Config;
import com.hutao.manage.component.Const;
import com.hutao.manage.component.MyConfig;
import com.hutao.manage.model.HospitalVisitAntibacterialDrugInfo;
import com.hutao.manage.model.HospitalVisitBasicInfo;
import com.hutao.manage.model.HospitalVisitCostInfo;
import com.hutao.manage.model.HospitalVisitCureInfo;
import com.hutao.manage.model.HospitalVisitDiseaseDiagInfo;
import com.hutao.manage.model.HospitalVisitDiseaseDiagRecord;
import com.hutao.manage.model.HospitalVisitDoctorAdviceStandingInfo;
import com.hutao.manage.model.HospitalVisitDoctorAdviceTemporaryInfo;
import com.hutao.manage.model.HospitalVisitDrugAllergyInfo;
import com.hutao.manage.model.HospitalVisitDrugAllergyRecord;
import com.hutao.manage.model.HospitalVisitExaminationReportsInfo;
import com.hutao.manage.model.HospitalVisitInfectionInfo;
import com.hutao.manage.model.HospitalVisitInfusionBloodInfo;
import com.hutao.manage.model.HospitalVisitIntensiveCareInfo;
import com.hutao.manage.model.HospitalVisitNurseInfo;
import com.hutao.manage.model.HospitalVisitOperateInfo;
import com.hutao.manage.model.HospitalVisitOperateRecord;
import com.hutao.manage.model.HospitalVisitPressureSoreInfo;
import com.hutao.manage.model.HospitalVisitTransferDeptInfo;
import com.hutao.manage.pojo.HospNoteVersion;
import com.hutao.manage.pojo.HospitalizationNote;
import com.hutao.manage.pojo.RespondResult;
import com.hutao.manage.pojo.cust.HospitalizationNoteBasic;
import com.hutao.manage.pojo.cust.MedicalRecordPrinterImage;
import com.hutao.manage.query.PrintPageDTO;
import com.hutao.manage.service.BaseInfoService;
import com.hutao.manage.service.HospNoteBasicJsonService;
import com.hutao.manage.service.HospitalNoteVersionService;
import com.hutao.manage.service.MedRecordService;
import com.hutao.manage.service.MedicalRecordService;
import com.hutao.manage.service.ScanFileService;
import com.hutao.manage.service.TreatmentTraceService;
import com.hutao.manage.util.CookieUtils;
import com.hutao.manage.util.DateUtil;
import com.hutao.manage.util.DiseaseValidateUtil;
import com.hutao.manage.util.FileUtil;
import com.hutao.manage.util.HttpClientUtil;
import com.hutao.manage.util.JsonUtil;
import com.hutao.manage.util.JsonUtils;
import com.hutao.manage.util.MD5;
import com.hutao.manage.util.PDFUtil;
import com.hutao.manage.util.PdfPigeonholeEnum;
import com.hutao.manage.util.Result;
import com.hutao.manage.util.StringUtil;
import com.hutao.manage.util.disk.DiskManageUtil;

@Controller
@RequestMapping("/medical_record")
public class MedicalRecordController {
	private static final Logger log = LoggerFactory.getLogger(MedicalRecordController.class);

	@Autowired
	private BaseInfoService baseInfoService;

	@Autowired
	private MyConfig myConfig;

	@Autowired
	private MedRecordService medRecordService;

	@Autowired
	private HospNoteBasicJsonService hospNoteBasicJsonService;

	@Autowired
	private MedicalRecordService medicalRecordService;

	@Autowired
	private TreatmentTraceService treatmentTraceService;

	@Autowired
	private HospitalNoteVersionService hospitalNoteVersionService;

	@Autowired
	private ScanFileService scanFileService;
	
	
	@Autowired
	private Config conf;
	
	@Value("${pdf.pigeonhole.dir}")
	private String pdfPigeonholeDir;

	@GetMapping("/edit_home_page_index_form")
	public String editHomePageIndexForm(String visitGuid, Model model) {
		model.addAttribute("visitGuid", visitGuid);
		return "medical_record/home_page/edit_index_info.catalogue";
	}

	/**
	 * 查看病案信息
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageIndexForm")
	public String searchHomePageIndexForm(String visitGuid, String fileName, Model model) {
		model.addAttribute("visitGuid", visitGuid);
		model.addAttribute("fileName", fileName);
		return "medical_record/search_page/edit_index_info.catalogue";
	}
	
	
	@ResponseBody
	@RequestMapping("/addSpecialMark")
	public String addSpecialMark(Integer noteId){
		int count = medRecordService.addSpecialMark(noteId);
		if(count>0){
			return "success";
		}else{
			return "failure";
		}
	}

	@SuppressWarnings("unchecked")
	@GetMapping("/edit_home_page_basic_form")
	public String editHomePageBasicForm(String visitGuid, String fileName, Model model) {
		List<Map<String, Object>> hospitalVisitDatas = medRecordService
				.getHospitalizationNoteBasicByFirstGuid(visitGuid);
		Map<String, Object> hospitalVisitData = new HashMap<String, Object>();
		
		if (hospitalVisitDatas.size() > 0) {
			hospitalVisitData = hospitalVisitDatas.get(0);
		}
		
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageBasic();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		if (StringUtils.isNotBlank(fileName)) {
			//从本地文件版本version中读取
			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;

			String currentFilePath = versionFilePath + fileName;
			String currentDiskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), currentFilePath);
			
			if (StringUtils.isBlank(currentDiskName)) {
				log.error("病案修改留痕在磁盘{}中, 找不到filePath={}这个版本的文件, visitGuid={}",
						config.getConfigFileStorageAllDisk(), currentFilePath, visitGuid);
			}
			
			jsonMap = readLineFile(currentDiskName + versionFilePath.trim().substring(1), versionFileName);
		} else {
			//从数据库中读取json数据
			String hospitalVisitDataJson = hospNoteBasicJsonService
						.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
					jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		
		Map<String, Object> hospitalVisit = (Map<String, Object>) jsonMap.get("basicInfo");
		
		if (hospitalVisit == null) {
			hospitalVisit = new HashMap<String, Object>();
			Date outHospitalDateTime = (Date) hospitalVisitData.get("out_hospital_date");
			if (outHospitalDateTime != null) {
				hospitalVisit.put("outHospitalDateTime",
						DateUtil.dateFormat(DateUtil.DATE_FORMATE, outHospitalDateTime));
			}
			Date inHospitalDateTime = (Date) hospitalVisitData.get("in_hospital_date");
			if (inHospitalDateTime != null) {
				hospitalVisit.put("inHospitalDateTime",
						DateUtil.dateFormat(DateUtil.DATE_FORMATE, inHospitalDateTime));
			}
			String inHospitalTypeCode = (String) hospitalVisitData.get("inHospitalTypeCode");
			hospitalVisit.put("inHospitalTypeCode", inHospitalTypeCode);
			String inHospitalTypeName = (String) hospitalVisitData.get("inHospitalTypeName");
			hospitalVisit.put("inHospitalTypeName", inHospitalTypeName);

			String outHospitalTypeCode = (String) hospitalVisitData.get("outHospitalTypeCode");
			hospitalVisit.put("outHospitalTypeCode", outHospitalTypeCode);

			String outHospitalTypeName = (String) hospitalVisitData.get("outHospitalTypeName");
			hospitalVisit.put("outHospitalTypeName", outHospitalTypeName);

			String patientName = (String) hospitalVisitData.get("name");
			hospitalVisit.put("patientName", patientName);

			String sexCode = (String) hospitalVisitData.get("sexCode");
			hospitalVisit.put("sexCode", sexCode);

			String sexName = (String) hospitalVisitData.get("sexName");
			hospitalVisit.put("sexName", sexName);

			String idDocumentTypeCode = (String) hospitalVisitData.get("idTypeCode");
			hospitalVisit.put("idDocumentTypeCode", idDocumentTypeCode);

			String idDocumentTypeName = (String) hospitalVisitData.get("idTypeName");
			hospitalVisit.put("idDocumentTypeName", idDocumentTypeName);

			String idNumber = (String) hospitalVisitData.get("id_number");
			hospitalVisit.put("idNumber", idNumber);

			Date birthday = (Date) hospitalVisitData.get("birthday");
			if (birthday != null) {
				hospitalVisit.put("birthday", DateUtil.dateFormat(DateUtil.DATE_FORMATE, birthday));
			}

			String mrId = (String) hospitalVisitData.get("mr_id");
			hospitalVisit.put("mrId", mrId);

			String onlyId = (String) hospitalVisitData.get("only_id");
			hospitalVisit.put("onlyId", onlyId);

			String hospitalCode = (String) hospitalVisitData.get("hospital_code");
			hospitalVisit.put("hospitalCode", hospitalCode);

			String hospitalName = (String) hospitalVisitData.get("hospital_name");
			hospitalVisit.put("hospitalName", hospitalName);

			String inDeptCode = (String) hospitalVisitData.get("inDeptCode");
			hospitalVisit.put("inDeptCode", inDeptCode);

			String inDeptName = (String) hospitalVisitData.get("inDeptName");
			hospitalVisit.put("inDeptName", inDeptName);

			String outDeptCode = (String) hospitalVisitData.get("outDeptCode");
			hospitalVisit.put("outDeptCode", outDeptCode);

			String outDeptName = (String) hospitalVisitData.get("outDeptName");
			hospitalVisit.put("outDeptName", outDeptName);

			String permanentAddress = (String) hospitalVisitData.get("address_no");
			hospitalVisit.put("permanentAddress", permanentAddress);
		}

		/*
		 * if (hospitalVisit.get("age") == null) { Date outHospitalDateTime =
		 * (Date) hospitalVisitData.get("out_hospital_date"); Date birthday =
		 * (Date) hospitalVisitData.get("birthday");
		 * 
		 * if (outHospitalDateTime != null && birthday != null) { long diff =
		 * outHospitalDateTime.getTime() - birthday.getTime();
		 * 
		 * hospitalVisit.put("age", (diff / (1000 * 60 * 60 * 24)) / 365); }
		 * 
		 * }
		 */
		String hospitalVisitJson = JsonUtil.objectToJson(hospitalVisit);
		model.addAttribute("hospitalVisitJson", hospitalVisitJson);
		model.addAttribute("hospitalVisit", hospitalVisit);
		return "medical_record/home_page/edit_basic_info";
	}

	/**
	 * 查看病案基本信息
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@GetMapping("/searchHomePageBasicForm")
	public String searchHomePageBasicForm(String visitGuid, String fileName, Model model) {
		List<Map<String, Object>> hospitalVisitDatas = medRecordService
				.getHospitalizationNoteBasicByFirstGuid(visitGuid);
		Map<String, Object> hospitalVisitData = new HashMap<String, Object>();
		if (hospitalVisitDatas.size() > 0) {
			hospitalVisitData = hospitalVisitDatas.get(0);
		}
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageBasic();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {
			if (visitGuid != null && visitGuid.length() > 0) {
				String hospitalVisitDataJson = hospNoteBasicJsonService
						.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
				if (hospitalVisitDataJson != null) {
					jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				}
				/*
				 * String filePath = myConfig.getHospitalVisitJsonPath() +
				 * StringUtil.getLocalPath(visitGuid); String fileName =
				 * visitGuid + ".json"; jsonMap = readLineFile(filePath,
				 * fileName);
				 */
			}
		}

		Map<String, Object> hospitalVisit = (Map<String, Object>) jsonMap.get("basicInfo");
		if (hospitalVisit == null) {
			hospitalVisit = new HashMap<String, Object>();
			Date outHospitalDateTime = (Date) hospitalVisitData.get("out_hospital_date");
			if (outHospitalDateTime != null) {
				hospitalVisit.put("outHospitalDateTime",
						DateUtil.dateFormat(DateUtil.DATE_FORMATE, outHospitalDateTime));
			}
			Date inHospitalDateTime = (Date) hospitalVisitData.get("in_hospital_date");
			if (inHospitalDateTime != null) {
				hospitalVisit.put("inHospitalDateTime",
						DateUtil.dateFormat(DateUtil.DATE_FORMATE, inHospitalDateTime));
			}
			String inHospitalTypeCode = (String) hospitalVisitData.get("inHospitalTypeCode");
			hospitalVisit.put("inHospitalTypeCode", inHospitalTypeCode);
			String inHospitalTypeName = (String) hospitalVisitData.get("inHospitalTypeName");
			hospitalVisit.put("inHospitalTypeName", inHospitalTypeName);

			String outHospitalTypeCode = (String) hospitalVisitData.get("outHospitalTypeCode");
			hospitalVisit.put("outHospitalTypeCode", outHospitalTypeCode);

			String outHospitalTypeName = (String) hospitalVisitData.get("outHospitalTypeName");
			hospitalVisit.put("outHospitalTypeName", outHospitalTypeName);

			String patientName = (String) hospitalVisitData.get("name");
			hospitalVisit.put("patientName", patientName);

			String sexCode = (String) hospitalVisitData.get("sexCode");
			hospitalVisit.put("sexCode", sexCode);

			String sexName = (String) hospitalVisitData.get("sexName");
			hospitalVisit.put("sexName", sexName);

			String idDocumentTypeCode = (String) hospitalVisitData.get("idTypeCode");
			hospitalVisit.put("idDocumentTypeCode", idDocumentTypeCode);

			String idDocumentTypeName = (String) hospitalVisitData.get("idTypeName");
			hospitalVisit.put("idDocumentTypeName", idDocumentTypeName);

			String idNumber = (String) hospitalVisitData.get("id_number");
			hospitalVisit.put("idNumber", idNumber);

			Date birthday = (Date) hospitalVisitData.get("birthday");
			if (birthday != null) {
				hospitalVisit.put("birthday", DateUtil.dateFormat(DateUtil.DATE_FORMATE, birthday));
			}

			String mrId = (String) hospitalVisitData.get("mr_id");
			hospitalVisit.put("mrId", mrId);

			String onlyId = (String) hospitalVisitData.get("only_id");
			hospitalVisit.put("onlyId", onlyId);

			String hospitalCode = (String) hospitalVisitData.get("hospital_code");
			hospitalVisit.put("hospitalCode", hospitalCode);

			String hospitalName = (String) hospitalVisitData.get("hospital_name");
			hospitalVisit.put("hospitalName", hospitalName);

			String inDeptCode = (String) hospitalVisitData.get("inDeptCode");
			hospitalVisit.put("inDeptCode", inDeptCode);

			String inDeptName = (String) hospitalVisitData.get("inDeptName");
			hospitalVisit.put("inDeptName", inDeptName);

			String outDeptCode = (String) hospitalVisitData.get("outDeptCode");
			hospitalVisit.put("outDeptCode", outDeptCode);

			String outDeptName = (String) hospitalVisitData.get("outDeptName");
			hospitalVisit.put("outDeptName", outDeptName);

			String permanentAddress = (String) hospitalVisitData.get("address_no");
			hospitalVisit.put("permanentAddress", permanentAddress);
		}

		/*
		 * if (hospitalVisit.get("age") == null) { Date outHospitalDateTime =
		 * (Date) hospitalVisitData.get("out_hospital_date"); Date birthday =
		 * (Date) hospitalVisitData.get("birthday");
		 * 
		 * if (outHospitalDateTime != null && birthday != null) { long diff =
		 * outHospitalDateTime.getTime() - birthday.getTime();
		 * 
		 * hospitalVisit.put("age", (diff / (1000 * 60 * 60 * 24)) / 365); }
		 * 
		 * }
		 */

		System.out.println(hospitalVisit);
		String hospitalVisitJson = JsonUtil.objectToJson(hospitalVisit);
		model.addAttribute("hospitalVisitJson", hospitalVisitJson);
		model.addAttribute("hospitalVisit", hospitalVisit);
		model.addAttribute("fileName", fileName);
		return "medical_record/search_page/edit_basic_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_basic")
	public String editHomePageBasic(HospitalVisitBasicInfo hospitalVisit, HttpServletRequest request, Model model) {
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(hospitalVisit.getVisitGuid());
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + hospitalVisit.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";
		String fileName = hospitalVisit.getVisitGuid() + ".json";
		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		//写入到本地json文件
		String realFilePath = diskName + filePath.trim().substring(1);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, hospitalVisit.getVisitGuid());
			return "medical_record/home_page/edit_basic_info";
		}
		
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		medicalRecordService.updateHospitalizationNoteBasic(hospitalVisit);
		Map<String,Object> basicInfoMap = (Map<String, Object>) jsonMap.get("basicInfo");
		
		//更新时添加原来的疾病和手术信息
		if(basicInfoMap!=null){
			hospitalVisit.setMainDiseaseName(basicInfoMap.get("mainDiseaseName")==null?"":(String)basicInfoMap.get("mainDiseaseName"));
			hospitalVisit.setMainDiseaseCode(basicInfoMap.get("mainDiseaseCode")==null?"":(String)basicInfoMap.get("mainDiseaseCode"));
			hospitalVisit.setSecondDiseaseName(basicInfoMap.get("secondDiseaseName")==null?"":(String)basicInfoMap.get("secondDiseaseName"));
			hospitalVisit.setSecondDiseaseCode(basicInfoMap.get("secondDiseaseCode")==null?"":(String)basicInfoMap.get("secondDiseaseCode"));
			hospitalVisit.setFirstOperationName(basicInfoMap.get("firstOperationName")==null?"":(String)basicInfoMap.get("firstOperationName"));
			hospitalVisit.setFirstOperationCode(basicInfoMap.get("firstOperationCode")==null?"":(String)basicInfoMap.get("firstOperationCode"));
			hospitalVisit.setSecondOperationName(basicInfoMap.get("secondOperationName")==null?"":(String)basicInfoMap.get("secondOperationName"));
			hospitalVisit.setSecondOperationCode(basicInfoMap.get("secondOperationCode")==null?"":(String)basicInfoMap.get("secondOperationCode"));
		}
		
		jsonMap.put("basicInfo", hospitalVisit);
		jsonMap.put("userId", currentUser);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(hospitalVisit.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(hospitalVisit.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("basicInfo", hospitalVisit);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(hospitalVisit.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
				
			} else {
				jsonDataMap.put("firstGuid", hospitalVisit.getVisitGuid());
				jsonDataMap.put("basicInfo", hospitalVisit);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageBasic();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", hospitalVisit.getVisitGuid());

		String hospitalVisitJson = JsonUtil.objectToJson(hospitalVisit);
		
		model.addAttribute("hospitalVisitJson", hospitalVisitJson);
		model.addAttribute("hospitalVisit", (Map<String, Object>) jsonMap.get("basicInfo"));
		
		return "medical_record/home_page/edit_basic_info";
	}

	@GetMapping("/edit_home_page_cure_form")
	public String editHomePageCureForm(HttpServletRequest request,String visitGuid, Model model) {
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageCure();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		
		@SuppressWarnings("unchecked")
		Map<String, Object> cureInfo = (Map<String, Object>) jsonMap.get("cureInfo");
		
		if (cureInfo == null) {
			cureInfo = new HashMap<String, Object>();
		}else{
			if(cureInfo.get("qualityControlDateTime")==null){
				cureInfo.put("qualityControlDateTime",DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
			}
		}
		
		//String currentUser = CookieUtils.getCookieValue(request, "userName");
		String cureInfoJson = JsonUtil.objectToJson(cureInfo);
		model.addAttribute("currentUser", currentUser);
		model.addAttribute("cureInfoJson", cureInfoJson);
		model.addAttribute("cureInfo", cureInfo);
		
		return "medical_record/home_page/edit_cure_info";
	}

	/**
	 * 查看病案治疗信息
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/editSearchPageCureForm")
	public String editSearchPageCureForm(HttpServletRequest request,String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageCure();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}

		@SuppressWarnings("unchecked")
		Map<String, Object> cureInfo = (Map<String, Object>) jsonMap.get("cureInfo");
		if (cureInfo == null) {
			cureInfo = new HashMap<String, Object>();
		}else{
			if(cureInfo.get("qualityControlDateTime")==null){
				cureInfo.put("qualityControlDateTime", DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
			}
		}
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		String cureInfoJson = JsonUtil.objectToJson(cureInfo);
		model.addAttribute("currentUser", currentUser);
		model.addAttribute("cureInfoJson", cureInfoJson);
		model.addAttribute("cureInfo", cureInfo);
		return "medical_record/search_page/edit_cure_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_cure")
	public String editHomePageCure(HospitalVisitCureInfo cureInfo, HttpServletRequest request, Model model) {
		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(cureInfo.getVisitGuid());
		String fileName = cureInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + cureInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";
		
		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		//写入到本地json文件
		String realFilePath = diskName + filePath.trim().substring(1);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, cureInfo.getVisitGuid());
			return "medical_record/home_page/edit_cure_info";
		} 
		
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		jsonMap.put("cureInfo", cureInfo);
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
	
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(cureInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(cureInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
		
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("cureInfo", cureInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(cureInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", cureInfo.getVisitGuid());
				jsonDataMap.put("cureInfo", cureInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
			
			
			/*RespondResult respondResult = new RespondResult(false, "500", "初始化错误", "");
			if (myConfig.getDataReturnConfig() != null && myConfig.getDataReturnConfig() == Const.DataReturn.RETURNED) {
				Map<String, Object> basicInfo = (Map<String, Object>) jsonMap.get("basicInfo");
				if (basicInfo != null) {
					Map<String, Object> requestParams = new HashMap<String, Object>();
					requestParams.put("mrId", (String) basicInfo.get("mrId"));
					requestParams.put("visitNumber", ((Integer) basicInfo.get("visitNumber")).intValue() + "");
					requestParams.put("cureInfo", cureInfo);
					String respondJson = HttpClientUtil.doPostJson(myConfig.getDataReturnCruePath(), requestParams);

					JSONObject respondMap = JSONObject.parseObject(respondJson);
					boolean result = (boolean) respondMap.get("success");
					if (result) {
						respondResult = new RespondResult(true, "200", "保存成功", "");
					} else {
						respondResult = new RespondResult(false, "500", "同步数据错误", "");
					}
				} else {
					respondResult = new RespondResult(true, "200", "保存成功", "");
				}
			}*/
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);
		String cureInfoJson = JsonUtil.objectToJson(cureInfo);
		model.addAttribute("cureInfoJson", cureInfoJson);
		model.addAttribute("cureInfo", (Map<String, Object>) jsonMap.get("cureInfo"));
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageCure();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", cureInfo.getVisitGuid());
		
		return "medical_record/home_page/edit_cure_info";
	}

	/**
	 * 查看疾病诊断信息
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageDiagForm")
	public String searchHomePageDiagForm(String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageDiag();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}

		Map<String, Object> diseaseDiagInfo = (Map<String, Object>) jsonMap.get("diseaseDiagInfo");
		Map<String, Object> basicInfo = (Map<String, Object>) jsonMap.get("basicInfo");
		diseaseDiagInfo = validateDiseaseDiagInfo(basicInfo, diseaseDiagInfo);

		if (diseaseDiagInfo == null) {
			diseaseDiagInfo = new HashMap<String, Object>();
		}
		String diseaseDiagInfoJson = JsonUtil.objectToJson(diseaseDiagInfo);
		model.addAttribute("diseaseDiagInfoJson", diseaseDiagInfoJson);
		return "medical_record/search_page/edit_diag_info";
	}

	@GetMapping("/edit_home_page_diag_form")
	public String editHomePageDiagForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageDiag();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}

		Map<String, Object> basicInfo = (Map<String, Object>) jsonMap.get("basicInfo");
		Map<String, Object> diseaseDiagInfo = (Map<String, Object>) jsonMap.get("diseaseDiagInfo");

		System.out.println(diseaseDiagInfo);

		diseaseDiagInfo = validateDiseaseDiagInfo(basicInfo, diseaseDiagInfo);

		if (diseaseDiagInfo == null) {
			diseaseDiagInfo = new HashMap<String, Object>();
		}

		String diseaseDiagInfoJson = JsonUtil.objectToJson(diseaseDiagInfo);
		model.addAttribute("diseaseDiagInfoJson", diseaseDiagInfoJson);
		return "medical_record/home_page/edit_diag_info";
	}

	/**
	 * 校验疾病信息
	 * 
	 * @return
	 */
	public Map<String, Object> validateDiseaseDiagInfo(Map<String, Object> basicInfoMap,
			Map<String, Object> diseaseDiagInfoMap) {
		try {
			if (MapUtils.isEmpty(diseaseDiagInfoMap)) {
				return null;
			}

			Integer age = (Integer) basicInfoMap.get("age");

			String sexName = (String) basicInfoMap.get("sexName");

			String autopsyCode = (String) basicInfoMap.get("autopsyCode");

			System.out.println(basicInfoMap);

			List<Map<String, Object>> diseaseDiagRecords = (List<Map<String, Object>>) diseaseDiagInfoMap
					.get("diseaseDiagRecords");
			if (CollectionUtils.isEmpty(diseaseDiagRecords)) {
				return diseaseDiagInfoMap;
			}

			String diagTypeCode = null;
			String diseaseDiagCode = null;
			for (Map<String, Object> diseaseDiagMap : diseaseDiagRecords) {
				// {diagTypeCode=3, diagTypeName=null, diagSortIndex=1,
				// treatDayNumber=3, diseaseDiagCode=V87.702,
				// diseaseDiagName=与火车碰撞的机动车交通事故-V87.702, operateMarkCode=0,
				// operateMarkName=非手术治疗, treatResultCode=ZY,
				// treatResultName=治愈,
				// confirmedDateTime=2018-03-20 15:10:54,
				// diseaseDiagOriginalDesc=}
				diagTypeCode = (String) diseaseDiagMap.get("diagTypeCode");
				diseaseDiagCode = (String) diseaseDiagMap.get("diseaseDiagCode");
				// 主要诊断：A～U开头和Z开头的编码；不包括字母V、W、X、Y开头的编码
				if (!DiseaseValidateUtil.validateMainDiseaseTypeRule(diagTypeCode, diseaseDiagCode)) {
					diseaseDiagMap.put("dataContent", "主要诊断：A～U开头和Z开头的编码；不包括字母V、W、X、Y开头的编码");
				}
				
				
				if (!DiseaseValidateUtil.validateDiagCode(diagTypeCode, diseaseDiagCode)) {
					diseaseDiagMap.put("dataContent", "疾病编码为空!");
				}

				// 其它诊断编码范围应为：A～Z开头
				if (!DiseaseValidateUtil.validateOtherDiseaseTypeRule(diagTypeCode, diseaseDiagCode, "A")) {
					diseaseDiagMap.put("dataContent", "其它诊断编码范围应为：A～Z开头");
				}

				// 门（急）诊诊断编码范围应为：A～Z开头
				if (!DiseaseValidateUtil.validateOtherDiseaseTypeRule(diagTypeCode, diseaseDiagCode, "1")) {
					diseaseDiagMap.put("dataContent", "门（急）诊诊断编码范围应为：A～Z开头");
				}
				//
				if (StringUtils.isNotEmpty(autopsyCode)) {

				}

				if (age != null) {

					// 5岁以上12岁以下儿童出院诊断不应编为P00-P96(起源于围产期的某些情况
					if (!DiseaseValidateUtil.validateChildDisease(age, diagTypeCode, diseaseDiagCode,
							DiseaseValidateUtil.P00_P96)) {
						diseaseDiagMap.put("dataContent", "5岁以上12岁以下儿童出院诊断不应编为P00-P96(起源于围产期的某些情况)");
					}

					// 12岁及以下儿童出院诊断不应编为O00-O99(妊娠、分娩和产褥期疾病)
					if (!DiseaseValidateUtil.validateChildDisease(age, diagTypeCode, diseaseDiagCode,
							DiseaseValidateUtil.O00_O99)) {
						diseaseDiagMap.put("dataContent", "12岁及以下儿童出院诊断不应编为O00-O99(妊娠、分娩和产褥期疾病)");
					}
					
					
				
					
					// 12岁及以下儿童出院诊断不应编为C50-C63(乳房、女性及男性生殖器恶性肿瘤)
					if (!DiseaseValidateUtil.validateChildDisease(age, diagTypeCode, diseaseDiagCode,
							DiseaseValidateUtil.C50_C63)) {
						diseaseDiagMap.put("dataContent", "12岁及以下儿童出院诊断不应编为C50-C63(乳房、女性及男性生殖器恶性肿瘤)");
					}

					// 12岁及以下儿童出院诊断一般不应编"D24-D29"(乳房、女性及男性生殖器官良性肿瘤)
					if (!DiseaseValidateUtil.validateChildDisease(age, diagTypeCode, diseaseDiagCode,
							DiseaseValidateUtil.D24_D29)) {
						diseaseDiagMap.put("dataContent", "12岁及以下儿童出院诊断一般不应编D24_D29(乳房、女性及男性生殖器官良性肿瘤)");
					}

				}

				if (StringUtils.isNotEmpty(sexName)) {
					Result result = DiseaseValidateUtil.validateManDisease(sexName, diagTypeCode, diseaseDiagCode);
					if (!result.isSuccess()) {
						diseaseDiagMap.put("dataContent", result.getMsg());
					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return diseaseDiagInfoMap;
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_diag")
	public String editHomePageDiag(HospitalVisitDiseaseDiagInfo diseaseDiagInfo, HttpServletRequest request,
			Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(diseaseDiagInfo.getVisitGuid());
		String fileName = diseaseDiagInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + diseaseDiagInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";
		
		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		//写入到本地json文件
		String realFilePath = diskName + filePath.trim().substring(1);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, diseaseDiagInfo.getVisitGuid());
			return "redirect:/medical_record/edit_home_page_diag_form?visitGuid=" + diseaseDiagInfo.getVisitGuid();
		} 
		
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		diseaseDiagInfo.clearEmpty();
		Collections.sort(diseaseDiagInfo.getDiseaseDiagRecords(),
				new HospitalVisitDiseaseDiagRecord.DiseaseDiagRecordComparator());
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("diseaseDiagInfo", diseaseDiagInfo);
		Map<String,Object> basicInfoMap = (Map<String, Object>) jsonMap.get("basicInfo");
		
		//更新basicInfo中的疾病信息
		if(diseaseDiagInfo!=null){
			 List<HospitalVisitDiseaseDiagRecord> diseaseDiagRecordList= diseaseDiagInfo.getDiseaseDiagRecords();
			 if(CollectionUtils.isNotEmpty(diseaseDiagRecordList)){
				 for (HospitalVisitDiseaseDiagRecord hospitalVisitDiseaseDiagRecord : diseaseDiagRecordList) {
					if("3".equals(hospitalVisitDiseaseDiagRecord.getDiagTypeCode())){
						if(basicInfoMap!=null){
							if(StringUtils.isNotEmpty(hospitalVisitDiseaseDiagRecord.getDiseaseDiagName())){
								basicInfoMap.put("mainDiseaseName", hospitalVisitDiseaseDiagRecord.getDiseaseDiagName().split("-")[0]);
								basicInfoMap.put("mainDiseaseCode", hospitalVisitDiseaseDiagRecord.getDiseaseDiagName().split("-")[1]);
							}
							
						}
					}
					
					if("A".equals(hospitalVisitDiseaseDiagRecord.getDiagTypeCode()) && hospitalVisitDiseaseDiagRecord.getDiagSortIndex()!=null &&  hospitalVisitDiseaseDiagRecord.getDiagSortIndex()==1){
						if(basicInfoMap!=null){
							if(StringUtils.isNotEmpty(hospitalVisitDiseaseDiagRecord.getDiseaseDiagName())){
								basicInfoMap.put("secondDiseaseName", hospitalVisitDiseaseDiagRecord.getDiseaseDiagName().split("-")[0]);
								basicInfoMap.put("secondDiseaseCode",  hospitalVisitDiseaseDiagRecord.getDiseaseDiagName().split("-")[1]);
							}
							
						}
					}
				}
			 }  
			 Collections.sort(diseaseDiagRecordList,  new HospitalVisitDiseaseDiagRecord.DiseaseDiagRecordComparator());
			 diseaseDiagInfo.setDiseaseDiagRecords(diseaseDiagRecordList);
		}
		
		jsonMap.put("basicInfo", basicInfoMap);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		RespondResult respondResult = new RespondResult(false, "500", "初始错误", "");
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(diseaseDiagInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(diseaseDiagInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("diseaseDiagInfo", diseaseDiagInfo);
				jsonDataMap.put("basicInfo", basicInfoMap);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(diseaseDiagInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", diseaseDiagInfo.getVisitGuid());
				jsonDataMap.put("diseaseDiagInfo", diseaseDiagInfo);
				jsonDataMap.put("basicInfo", basicInfoMap);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
			
			
			if (myConfig.getDataReturnConfig() != null && myConfig.getDataReturnConfig() == Const.DataReturn.RETURNED) {
				Map<String, Object> basicInfo = (Map<String, Object>) jsonMap.get("basicInfo");
				if (basicInfo != null) {
					Map<String, Object> requestParams = new HashMap<String, Object>();
					requestParams.put("mrId", (String) basicInfo.get("mrId"));
					requestParams.put("visitNumber", ((Integer) basicInfo.get("visitNumber")).intValue() + "");
					requestParams.put("diseaseDiagRecords", diseaseDiagInfo.getDiseaseDiagRecords());
					String respondJson = HttpClientUtil.doPostJson(myConfig.getDataReturnDiagPath(), requestParams);

					JSONObject respondMap = JSONObject.parseObject(respondJson);
					boolean result = (boolean) respondMap.get("success");
					if (result) {
						respondResult = new RespondResult(true, "200", "保存成功", "");
					} else {
						respondResult = new RespondResult(false, "500", "同步数据错误", "");
					}
				} else {
					respondResult = new RespondResult(true, "200", "保存成功", "");
				}
			}

			/*
			 * Map<String, Object> requestParams = new HashMap<String,
			 * Object>(); requestParams.put("mrId", "BN00001");
			 * requestParams.put("visitNumber","1");
			 * requestParams.put("diseaseDiagRecords",
			 * diseaseDiagInfo.getDiseaseDiagRecords()); String userJson =
			 * HttpClientUtil.doPostJson(
			 * "http://localhost:8887/medical-export/export305/ajaxSynchronizDiagInfo",
			 * requestParams); JSONObject userMap =
			 * JSONObject.parseObject(userJson);
			 */

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respondResult = new RespondResult(false, "500", "未知错误", e.getMessage());
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageDiag();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);

		model.addAttribute("visitGuid", diseaseDiagInfo.getVisitGuid());
		String diseaseDiagInfoJson = JsonUtil.objectToJson(diseaseDiagInfo);
		model.addAttribute("diseaseDiagInfoJson", diseaseDiagInfoJson);
		model.addAttribute("respondResultJson", JsonUtil.objectToJson(respondResult));
		
		// return "medical_record/home_page/edit_diag_info";
		return "redirect:/medical_record/edit_home_page_diag_form?visitGuid=" + diseaseDiagInfo.getVisitGuid();
	}

	@GetMapping("/edit_home_page_operate_form")
	public String editHomePageOperateForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageOperate();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
	
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
	
		Map<String, Object> operateInfo = (Map<String, Object>) jsonMap.get("operateInfo");
		
		if (operateInfo == null) {
			operateInfo = new HashMap<String, Object>();
		}
		
		String operateInfoJson = JsonUtil.objectToJson(operateInfo);
		model.addAttribute("operateInfo", operateInfo);
		model.addAttribute("operateInfoJson", operateInfoJson);
		
		return "medical_record/home_page/edit_operate_info";
	}

	/**
	 * 查看手术信息
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageOperateForm")
	public String searchHomePageOperateForm(String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageOperate();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> operateInfo = (Map<String, Object>) jsonMap.get("operateInfo");
		if (operateInfo == null) {
			operateInfo = new HashMap<String, Object>();
		}
		String operateInfoJson = JsonUtil.objectToJson(operateInfo);
		model.addAttribute("operateInfo", operateInfo);
		model.addAttribute("operateInfoJson", operateInfoJson);
		return "medical_record/search_page/edit_operate_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_operate")
	public String editHomePageOperate(HospitalVisitOperateInfo operateInfo, HttpServletRequest request, Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(operateInfo.getVisitGuid());
		String fileName = operateInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + operateInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";
		
		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		//写入到本地json文件
		String realFilePath = diskName + filePath.trim().substring(1);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, operateInfo.getVisitGuid());
			return "medical_record/home_page/edit_operate_info";
		}
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		operateInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		 List<HospitalVisitOperateRecord> operationRecords = operateInfo.getOperateRecords();
		 if(CollectionUtils.isNotEmpty(operationRecords)){
			 Collections.sort(operationRecords, new HospitalVisitOperateRecord());
		 }
		jsonMap.put("operateInfo", operateInfo);
		
		Map<String, Object> basicInfo = (Map<String, Object>) jsonMap.get("basicInfo");
		
		
		 List<HospitalVisitOperateRecord> operationList = operateInfo.getOperateRecords();
		 
		 if(CollectionUtils.isNotEmpty(operationList)){
			 for (HospitalVisitOperateRecord hospitalVisitOperateRecord : operationList) {
				 if(basicInfo!=null){
					 if(hospitalVisitOperateRecord.getOperateSortIndex()!=null && hospitalVisitOperateRecord.getOperateSortIndex()==1){
						 if(StringUtils.isNotBlank(hospitalVisitOperateRecord.getOperateName())){
							 basicInfo.put("firstOperationName", hospitalVisitOperateRecord.getOperateName().split("-")[0]);
							 basicInfo.put("firstOperationCode", hospitalVisitOperateRecord.getOperateName().split("-")[1]);
						 }
					 }
					 
					 if(hospitalVisitOperateRecord.getOperateSortIndex()!=null && hospitalVisitOperateRecord.getOperateSortIndex()==2){
						 if(StringUtils.isNotBlank(hospitalVisitOperateRecord.getOperateName())){
							 basicInfo.put("secondOperationName", hospitalVisitOperateRecord.getOperateName().split("-")[0]);
							 basicInfo.put("secondOperationCode", hospitalVisitOperateRecord.getOperateName().split("-")[1]);
						 }
					 }
				 }
			}
		 }
		
		 jsonMap.put("basicInfo", basicInfo);
		RespondResult respondResult = new RespondResult(false, "500", "初始错误", "");
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		try {
				FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);

			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);			
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(operateInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(operateInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("operateInfo", operateInfo);
				jsonDataMap.put("basicInfo", basicInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(operateInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", operateInfo.getVisitGuid());
				jsonDataMap.put("operateInfo", operateInfo);
				jsonDataMap.put("basicInfo", basicInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
			if (myConfig.getDataReturnConfig() != null && myConfig.getDataReturnConfig() == Const.DataReturn.RETURNED) {
				
				if (basicInfo != null) {
					Map<String, Object> requestParams = new HashMap<String, Object>();
					requestParams.put("mrId", (String) basicInfo.get("mrId"));
					requestParams.put("visitNumber", ((Integer) basicInfo.get("visitNumber")).intValue() + "");
					requestParams.put("operateRecords", operateInfo.getOperateRecords());
					String respondJson = HttpClientUtil.doPostJson(myConfig.getDataReturnOperationPath(),
							requestParams);
					JSONObject respondMap = JSONObject.parseObject(respondJson);
					boolean result = (boolean) respondMap.get("success");
					if (result) {
						respondResult = new RespondResult(true, "200", "保存成功", "");
					} else {
						respondResult = new RespondResult(false, "500", "同步数据错误", "");
					}
				} else {
					respondResult = new RespondResult(true, "200", "保存成功", "");
				}

			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respondResult = new RespondResult(false, "500", "未知错误", e.getMessage());
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);
		model.addAttribute("visitGuid", operateInfo.getVisitGuid());
		String operateInfoJson = JsonUtil.objectToJson(operateInfo);
		model.addAttribute("operateInfoJson", operateInfoJson);
		model.addAttribute("operateInfo", (Map<String, Object>) jsonMap.get("operateInfo"));
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageOperate();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("respondResultJson", JsonUtil.objectToJson(respondResult));
		return "medical_record/home_page/edit_operate_info";
	}

	@GetMapping("/edit_home_page_infusion_blood_form")
	public String editHomePageInfusionBloodForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageInfusionBlood();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		
		Map<String, Object> infusionBloodInfo = (Map<String, Object>) jsonMap.get("infusionBloodInfo");
		if (infusionBloodInfo == null) {
			infusionBloodInfo = new HashMap<String, Object>();
		}
		String infusionBloodInfoJson = JsonUtil.objectToJson(infusionBloodInfo);
		model.addAttribute("infusionBloodInfoJson", infusionBloodInfoJson);
		model.addAttribute("infusionBloodInfo", infusionBloodInfo);
		
		return "medical_record/home_page/edit_infusion_blood_info";
	}

	/**
	 * 查看输血记录
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageInfusionBloodForm")
	public String searchHomePageInfusionBloodForm(String visitGuid, String fileName, Model model) {
		//获取血型字典
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageInfusionBlood();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> infusionBloodInfo = (Map<String, Object>) jsonMap.get("infusionBloodInfo");
		if (infusionBloodInfo == null) {
			infusionBloodInfo = new HashMap<String, Object>();
		}
		String infusionBloodInfoJson = JsonUtil.objectToJson(infusionBloodInfo);
		model.addAttribute("infusionBloodInfoJson", infusionBloodInfoJson);
		model.addAttribute("infusionBloodInfo", infusionBloodInfo);
		return "medical_record/search_page/edit_infusion_blood_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_infusion_blood")
	public String editHomePageInfusionBlood(HospitalVisitInfusionBloodInfo infusionBloodInfo,
			HttpServletRequest request, Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath()
				+ StringUtil.getLocalPath(infusionBloodInfo.getVisitGuid());
		String fileName = infusionBloodInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + infusionBloodInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, infusionBloodInfo.getVisitGuid());
			return "medical_record/home_page/edit_infusion_blood_info";
		} 
		
		String realFilePath = diskName + filePath.trim().substring(1);
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		
		/*infusionBloodInfo.clearEmpty();*/
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("infusionBloodInfo", infusionBloodInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		
		try {
				FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(infusionBloodInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(infusionBloodInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("infusionBloodInfo", infusionBloodInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(infusionBloodInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", infusionBloodInfo.getVisitGuid());
				jsonDataMap.put("infusionBloodInfo", infusionBloodInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String infusionBloodInfoJson = JsonUtil.objectToJson(infusionBloodInfo);
		model.addAttribute("infusionBloodInfoJson", infusionBloodInfoJson);
		model.addAttribute("infusionBloodInfo", (Map<String, Object>) jsonMap.get("infusionBloodInfo"));
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageInfusionBlood();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", infusionBloodInfo.getVisitGuid());
		return "medical_record/home_page/edit_infusion_blood_info";
	}

	@GetMapping("/edit_home_page_transfer_dept_form")
	public String editHomePageTransferDeptForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageTransferDept();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		
		Map<String, Object> transferDeptInfo = (Map<String, Object>) jsonMap.get("transferDeptInfo");
		if (transferDeptInfo == null) {
			transferDeptInfo = new HashMap<String, Object>();
		}
		String transferDeptInfoJson = JsonUtil.objectToJson(transferDeptInfo);
		model.addAttribute("transferDeptInfoJson", transferDeptInfoJson);
		return "medical_record/home_page/edit_transfer_dept_info";
	}

	/**
	 * 查看转科记录
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageTransferDeptForm")
	public String searchHomePageTransferDeptForm(String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageTransferDept();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();

		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> transferDeptInfo = (Map<String, Object>) jsonMap.get("transferDeptInfo");
		if (transferDeptInfo == null) {
			transferDeptInfo = new HashMap<String, Object>();
		}
		String transferDeptInfoJson = JsonUtil.objectToJson(transferDeptInfo);
		model.addAttribute("transferDeptInfoJson", transferDeptInfoJson);
		return "medical_record/search_page/edit_transfer_dept_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_transfer_dept")
	public String editHomePageTransferDept(HospitalVisitTransferDeptInfo transferDeptInfo, HttpServletRequest request,
			Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath()
				+ StringUtil.getLocalPath(transferDeptInfo.getVisitGuid());
		String fileName = transferDeptInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + transferDeptInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, transferDeptInfo.getVisitGuid());
			return "medical_record/home_page/edit_transfer_dept_info";
		} 
		
		String realFilePath = diskName + filePath.trim().substring(1);
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		transferDeptInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("transferDeptInfo", transferDeptInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		try {
			
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(transferDeptInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(transferDeptInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("transferDeptInfo", transferDeptInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(transferDeptInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", transferDeptInfo.getVisitGuid());
				jsonDataMap.put("transferDeptInfo", transferDeptInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String transferDeptInfoJson = JsonUtil.objectToJson(transferDeptInfo);
		model.addAttribute("transferDeptInfoJson", transferDeptInfoJson);
		model.addAttribute("transferDeptInfo", (Map<String, Object>) jsonMap.get("transferDeptInfo"));
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageTransferDept();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", transferDeptInfo.getVisitGuid());
		return "medical_record/home_page/edit_transfer_dept_info";
	}

	@GetMapping("/edit_home_page_drug_allergy_form")
	public String editHomePageDrugAllergyForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageAllergyDrug();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		
		Map<String, Object> drugAllergyInfo = (Map<String, Object>) jsonMap.get("drugAllergyInfo");
		if (drugAllergyInfo == null) {
			drugAllergyInfo = new HashMap<String, Object>();
		}
		String drugAllergyInfoJson = JsonUtil.objectToJson(drugAllergyInfo);
		model.addAttribute("drugAllergyInfoJson", drugAllergyInfoJson);
		model.addAttribute("drugAllergyInfo", drugAllergyInfo);
		
		return "medical_record/home_page/edit_drug_allergy_info";
	}

	/**
	 * 查看药物过敏信息
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageDrugAllergyForm")
	public String searchHomePageDrugAllergyForm(String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageAllergyDrug();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();

		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}

		@SuppressWarnings("unchecked")
		Map<String, Object> drugAllergyInfo = (Map<String, Object>) jsonMap.get("drugAllergyInfo");
		if (drugAllergyInfo == null) {
			drugAllergyInfo = new HashMap<String, Object>();
		}
		String drugAllergyInfoJson = JsonUtil.objectToJson(drugAllergyInfo);
		model.addAttribute("drugAllergyInfoJson", drugAllergyInfoJson);
		model.addAttribute("drugAllergyInfo", drugAllergyInfo);
		return "medical_record/search_page/edit_drug_allergy_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_drug_allergy")
	public String editHomePageDrugAllergy(HospitalVisitDrugAllergyInfo drugAllergyInfo, HttpServletRequest request,
			Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(drugAllergyInfo.getVisitGuid());
		String fileName = drugAllergyInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + drugAllergyInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";
		
		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, drugAllergyInfo.getVisitGuid());
			return "medical_record/home_page/edit_drug_allergy_info";
		} 
		
		String realFilePath = diskName + filePath.trim().substring(1);
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		drugAllergyInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("drugAllergyInfo", drugAllergyInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		RespondResult respondResult = new RespondResult(false, "500", "初始错误", "");
		
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(drugAllergyInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(drugAllergyInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("drugAllergyInfo", drugAllergyInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(drugAllergyInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", drugAllergyInfo.getVisitGuid());
				jsonDataMap.put("drugAllergyInfo", drugAllergyInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
			
			/*if (myConfig.getDataReturnConfig() != null && myConfig.getDataReturnConfig() == Const.DataReturn.RETURNED) {
				Map<String, Object> basicInfo = (Map<String, Object>) jsonMap.get("basicInfo");
				if (basicInfo != null) {
					Map<String, Object> requestParams = new HashMap<String, Object>();
					requestParams.put("mrId", (String) basicInfo.get("mrId"));
					requestParams.put("visitNumber", ((Integer) basicInfo.get("visitNumber")).intValue() + "");
					//requestParams.put("operateRecords", operateInfo.getOperateRecords());
					if(drugAllergyInfo!=null){
						 List<HospitalVisitDrugAllergyRecord> drugAllergyRecords= drugAllergyInfo.getDrugAllergyRecords();
						 if(CollectionUtils.isEmpty(drugAllergyRecords)){
							 requestParams.put("allergyDrugs", null);
						 }else{
							 HospitalVisitDrugAllergyRecord drugAllergyRecord=drugAllergyRecords.get(0);
							 String allergyDrugs=drugAllergyRecord.getDrugAllergyName();
							 if(StringUtils.isEmpty(allergyDrugs)){
								 requestParams.put("allergyDrugs", null);
							 }else{
								 requestParams.put("allergyDrugs", allergyDrugs);
							 }
						 }
					}else{
						requestParams.put("allergyDrugs", null);
					}
					String respondJson = HttpClientUtil.doPostJson(myConfig.getDataReturnAlergydrugPath(),
							requestParams);
					JSONObject respondMap = JSONObject.parseObject(respondJson);
					boolean result = (boolean) respondMap.get("success");
					if (result) {
						respondResult = new RespondResult(true, "200", "保存成功", "");
					} else {
						respondResult = new RespondResult(false, "500", "同步数据错误", "");
					}
				} else {
					respondResult = new RespondResult(true, "200", "保存成功", "");
				}

			}*/
		} catch (IOException e) {
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String drugAllergyInfoJson = JsonUtil.objectToJson(drugAllergyInfo);
		model.addAttribute("drugAllergyInfoJson", drugAllergyInfoJson);
		model.addAttribute("drugAllergyInfo", (Map<String, Object>) jsonMap.get("drugAllergyInfo"));

		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageAllergyDrug();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", drugAllergyInfo.getVisitGuid());
		
		return "medical_record/home_page/edit_drug_allergy_info";
	}

	@GetMapping("/edit_home_page_intensive_care_form")
	public String editHomePageIntensiveCareForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageIntensiveCare();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> intensiveCareInfo = (Map<String, Object>) jsonMap.get("intensiveCareInfo");
		if (intensiveCareInfo == null) {
			intensiveCareInfo = new HashMap<String, Object>();
		}
		String intensiveCareInfoJson = JsonUtil.objectToJson(intensiveCareInfo);
		model.addAttribute("intensiveCareInfoJson", intensiveCareInfoJson);
		model.addAttribute("intensiveCareInfo", intensiveCareInfo);
		return "medical_record/home_page/edit_intensive_care_info";
	}

	/**
	 * 查看重症监护
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageIntensiveCareForm")
	public String searchHomePageIntensiveCareForm(String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageIntensiveCare();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();

		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> intensiveCareInfo = (Map<String, Object>) jsonMap.get("intensiveCareInfo");
		if (intensiveCareInfo == null) {
			intensiveCareInfo = new HashMap<String, Object>();
		}
		String intensiveCareInfoJson = JsonUtil.objectToJson(intensiveCareInfo);
		model.addAttribute("intensiveCareInfoJson", intensiveCareInfoJson);
		model.addAttribute("intensiveCareInfo", intensiveCareInfo);
		return "medical_record/search_page/edit_intensive_care_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_intensive_care")
	public String editHomePageIntensiveCare(HospitalVisitIntensiveCareInfo intensiveCareInfo,
			HttpServletRequest request, Model model) {
		String filePath = myConfig.getHospitalVisitJsonPath()
				+ StringUtil.getLocalPath(intensiveCareInfo.getVisitGuid());
		// String versionFilePath = myConfig.getHospitalVisitJsonVersionPath()+
		// StringUtil.getLocalPath(intensiveCareInfo.getVisitGuid());
		String fileName = intensiveCareInfo.getVisitGuid() + ".json";
		// String versionFileName = intensiveCareInfo.getVisitGuid()+"-" +
		// DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + intensiveCareInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		Map<String, Object> jsonMap = readLineFile(filePath, fileName);
		intensiveCareInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("intensiveCareInfo", intensiveCareInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		try {
			FileUtil.createOrEditFile(jsonMapJson, filePath, fileName);
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(intensiveCareInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(intensiveCareInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("intensiveCareInfo", intensiveCareInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(intensiveCareInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", intensiveCareInfo.getVisitGuid());
				jsonDataMap.put("intensiveCareInfo", intensiveCareInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String intensiveCareInfoJson = JsonUtil.objectToJson(intensiveCareInfo);
		model.addAttribute("intensiveCareInfoJson", intensiveCareInfoJson);
		model.addAttribute("intensiveCareInfo", (Map<String, Object>) jsonMap.get("intensiveCareInfo"));

		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageIntensiveCare();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", intensiveCareInfo.getVisitGuid());
		return "medical_record/home_page/edit_intensive_care_info";
	}

	@GetMapping("/edit_home_page_nurse_form")
	public String editHomePageNurseForm(String visitGuid, Model model) {

		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}

		Map<String, Object> nurseInfo = (Map<String, Object>) jsonMap.get("nurseInfo");
		
		if (nurseInfo == null) {
			nurseInfo = new HashMap<String, Object>();
		}
		
		String nurseInfoJson = JsonUtil.objectToJson(nurseInfo);
		
		Map<String, Object> map = medicalRecordService.getHospitalizationNoteByFirstGuid(visitGuid);
		if (null != map) {
			model.addAttribute("mrId", map.get("mr_id"));
			model.addAttribute("visitNumber", map.get("visit_number"));
		}
		
		model.addAttribute("nurseInfoJson", nurseInfoJson);
		model.addAttribute("nurseInfo", nurseInfo);
		return "medical_record/home_page/edit_nurse_info";
	}

	/**
	 * 查看护理记录
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageNurseForm")
	public String searchHomePageNurseForm(String visitGuid, String fileName, Model model) {

		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> nurseInfo = (Map<String, Object>) jsonMap.get("nurseInfo");
		if (nurseInfo == null) {
			nurseInfo = new HashMap<String, Object>();
		}
		String nurseInfoJson = JsonUtil.objectToJson(nurseInfo);
		model.addAttribute("nurseInfoJson", nurseInfoJson);
		model.addAttribute("nurseInfo", nurseInfo);
		return "medical_record/search_page/edit_nurse_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_nurse")
	public String editHomePageNurse(HospitalVisitNurseInfo nurseInfo, HttpServletRequest request, Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(nurseInfo.getVisitGuid());
		String fileName = nurseInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + nurseInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, nurseInfo.getVisitGuid());
			return "medical_record/home_page/edit_nurse_info";
		} 
		
		String realFilePath = diskName + filePath.trim().substring(1);
			
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("nurseInfo", nurseInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(nurseInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(nurseInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("nurseInfo", nurseInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(nurseInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", nurseInfo.getVisitGuid());
				jsonDataMap.put("nurseInfo", nurseInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
			
			RespondResult respondResult = new RespondResult(false, "500", "初始错误", "");
			/*if (myConfig.getDataReturnConfig() != null && myConfig.getDataReturnConfig() == Const.DataReturn.RETURNED) {
				Map<String, Object> basicInfo = (Map<String, Object>) jsonMap.get("basicInfo");
				if (basicInfo != null) {
					Map<String, Object> requestParams = new HashMap<String, Object>();
					requestParams.put("mrId", (String) basicInfo.get("mrId"));
					requestParams.put("visitNumber", ((Integer) basicInfo.get("visitNumber")).intValue() + "");
					//requestParams.put("operateRecords", operateInfo.getOperateRecords());
					if(nurseInfo!=null){
						requestParams.put("nurseInfo", nurseInfo);
						String respondJson = HttpClientUtil.doPostJson(myConfig.getDataReturnNursedaysPath(),
								requestParams);
						JSONObject respondMap = JSONObject.parseObject(respondJson);
						boolean result = (boolean) respondMap.get("success");
						if (result) {
							respondResult = new RespondResult(true, "200", "保存成功", "");
						} else {
							respondResult = new RespondResult(false, "500", "同步数据错误", "");
						}
					}
				} else {
					respondResult = new RespondResult(true, "200", "保存成功", "");
				}

			}
*/
		} catch (IOException e) {
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String nurseInfoJson = JsonUtil.objectToJson(nurseInfo);
		model.addAttribute("nurseInfoJson", nurseInfoJson);
		model.addAttribute("nurseInfo", (Map<String, Object>) jsonMap.get("nurseInfo"));
		model.addAttribute("visitGuid", nurseInfo.getVisitGuid());
		
		return "medical_record/home_page/edit_nurse_info";
	}

	@GetMapping("/edit_home_page_pressure_sore_form")
	public String editHomePagePressureSoreForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePagePressureSore();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> pressureSoreInfo = (Map<String, Object>) jsonMap.get("pressureSoreInfo");
		if (pressureSoreInfo == null) {
			pressureSoreInfo = new HashMap<String, Object>();
		}
		String pressureSoreInfoJson = JsonUtil.objectToJson(pressureSoreInfo);
		model.addAttribute("pressureSoreInfoJson", pressureSoreInfoJson);
		model.addAttribute("pressureSoreInfo", pressureSoreInfo);
		return "medical_record/home_page/edit_pressure_sore_info";
	}

	@GetMapping("/searchHomePagePressureSoreForm")
	public String searchHomePagePressureSoreForm(String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePagePressureSore();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> pressureSoreInfo = (Map<String, Object>) jsonMap.get("pressureSoreInfo");
		if (pressureSoreInfo == null) {
			pressureSoreInfo = new HashMap<String, Object>();
		}
		String pressureSoreInfoJson = JsonUtil.objectToJson(pressureSoreInfo);
		model.addAttribute("pressureSoreInfoJson", pressureSoreInfoJson);
		model.addAttribute("pressureSoreInfo", pressureSoreInfo);
		return "medical_record/search_page/edit_pressure_sore_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_pressure_sore")
	public String editHomePagePressureSore(HospitalVisitPressureSoreInfo pressureSoreInfo, HttpServletRequest request,
			Model model) {
		String filePath = myConfig.getHospitalVisitJsonPath()
				+ StringUtil.getLocalPath(pressureSoreInfo.getVisitGuid());
		// String versionFilePath = myConfig.getHospitalVisitJsonVersionPath()+
		// StringUtil.getLocalPath(pressureSoreInfo.getVisitGuid());
		String fileName = pressureSoreInfo.getVisitGuid() + ".json";
		// String versionFileName = pressureSoreInfo.getVisitGuid()+"-" +
		// DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + pressureSoreInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		Map<String, Object> jsonMap = readLineFile(filePath, fileName);
		pressureSoreInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("pressureSoreInfo", pressureSoreInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		try {
			FileUtil.createOrEditFile(jsonMapJson, filePath, fileName);
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);

			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(pressureSoreInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(pressureSoreInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("pressureSoreInfo", pressureSoreInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(pressureSoreInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", pressureSoreInfo.getVisitGuid());
				jsonDataMap.put("pressureSoreInfo", pressureSoreInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String pressureSoreInfoJson = JsonUtil.objectToJson(pressureSoreInfo);
		model.addAttribute("pressureSoreInfoJson", pressureSoreInfoJson);
		model.addAttribute("pressureSoreInfo", (Map<String, Object>) jsonMap.get("pressureSoreInfo"));

		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePagePressureSore();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", pressureSoreInfo.getVisitGuid());
		return "medical_record/home_page/edit_pressure_sore_info";
	}

	@GetMapping("/edit_home_page_pregnancy_birth_form")
	public String editHomePagePregnancyBirthForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageBasic();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		return "medical_record/home_page/edit_pregnancy_birth_info";
	}

	@GetMapping("/edit_home_page_antibacterial_drug_form")
	public String editHomePageAntibacterialDrugForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageAntibacterialDrug();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> antibacterialDrugInfo = (Map<String, Object>) jsonMap.get("antibacterialDrugInfo");
		if (antibacterialDrugInfo == null) {
			antibacterialDrugInfo = new HashMap<String, Object>();
		}
		String antibacterialDrugInfoJson = JsonUtil.objectToJson(antibacterialDrugInfo);
		model.addAttribute("antibacterialDrugInfoJson", antibacterialDrugInfoJson);
		model.addAttribute("antibacterialDrugInfo", antibacterialDrugInfo);
		return "medical_record/home_page/edit_antibacterial_drug_info";
	}

	/**
	 * 查询抗菌药物
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageAntibacterialDrugForm")
	public String searchHomePageAntibacterialDrugForm(String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageAntibacterialDrug();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> antibacterialDrugInfo = (Map<String, Object>) jsonMap.get("antibacterialDrugInfo");
		if (antibacterialDrugInfo == null) {
			antibacterialDrugInfo = new HashMap<String, Object>();
		}
		String antibacterialDrugInfoJson = JsonUtil.objectToJson(antibacterialDrugInfo);
		model.addAttribute("antibacterialDrugInfoJson", antibacterialDrugInfoJson);
		model.addAttribute("antibacterialDrugInfo", antibacterialDrugInfo);
		return "medical_record/search_page/edit_antibacterial_drug_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_antibacterial_drug")
	public String editHomePageAntibacterialDrug(HospitalVisitAntibacterialDrugInfo antibacterialDrugInfo,
			HttpServletRequest request, Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath()
				+ StringUtil.getLocalPath(antibacterialDrugInfo.getVisitGuid());
		// String versionFilePath = myConfig.getHospitalVisitJsonVersionPath()+
		// StringUtil.getLocalPath(antibacterialDrugInfo.getVisitGuid());
		String fileName = antibacterialDrugInfo.getVisitGuid() + ".json";
		// String versionFileName = antibacterialDrugInfo.getVisitGuid()+"-" +
		// DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + antibacterialDrugInfo.getVisitGuid()
				+ "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		Map<String, Object> jsonMap = readLineFile(filePath, fileName);
		antibacterialDrugInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("antibacterialDrugInfo", antibacterialDrugInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		try {
			FileUtil.createOrEditFile(jsonMapJson, filePath, fileName);
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);

			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(antibacterialDrugInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(antibacterialDrugInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("antibacterialDrugInfo", antibacterialDrugInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(antibacterialDrugInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", antibacterialDrugInfo.getVisitGuid());
				jsonDataMap.put("antibacterialDrugInfo", antibacterialDrugInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String antibacterialDrugInfoJson = JsonUtil.objectToJson(antibacterialDrugInfo);
		model.addAttribute("antibacterialDrugInfoJson", antibacterialDrugInfoJson);
		model.addAttribute("antibacterialDrugInfo", (Map<String, Object>) jsonMap.get("antibacterialDrugInfo"));

		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageAntibacterialDrug();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", antibacterialDrugInfo.getVisitGuid());
		return "medical_record/home_page/edit_antibacterial_drug_info";
	}

	@GetMapping("/edit_home_page_infection_form")
	public String editHomePageInfectionForm(String visitGuid, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageInfection();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		
		Map<String, Object> infectionInfo = (Map<String, Object>) jsonMap.get("infectionInfo");
		if (infectionInfo == null) {
			infectionInfo = new HashMap<String, Object>();
		}
		String infectionInfoJson = JsonUtil.objectToJson(infectionInfo);
		model.addAttribute("infectionInfoJson", infectionInfoJson);
		model.addAttribute("infectionInfo", infectionInfo);
		
		return "medical_record/home_page/edit_infection_info";
	}

	/**
	 * 医院感染
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageInfectionForm")
	public String searchHomePageInfectionForm(String visitGuid, String fileName, Model model) {
		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageInfection();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> infectionInfo = (Map<String, Object>) jsonMap.get("infectionInfo");
		if (infectionInfo == null) {
			infectionInfo = new HashMap<String, Object>();
		}
		String infectionInfoJson = JsonUtil.objectToJson(infectionInfo);
		model.addAttribute("infectionInfoJson", infectionInfoJson);
		model.addAttribute("infectionInfo", infectionInfo);
		return "medical_record/search_page/edit_infection_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_infection")
	public String editHomePageInfection(HospitalVisitInfectionInfo infectionInfo, HttpServletRequest request,
			Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(infectionInfo.getVisitGuid());
		String fileName = infectionInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + infectionInfo.getVisitGuid() + "/";
		// 版本文件名称
		
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";
		
		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, infectionInfo.getVisitGuid());
			return "medical_record/home_page/edit_infection_info";
		} 
		
		String realFilePath = diskName + filePath.trim().substring(1);
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		//infectionInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("infectionInfo", infectionInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(infectionInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(infectionInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("infectionInfo", infectionInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(infectionInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
				
			} else {
				jsonDataMap.put("firstGuid", infectionInfo.getVisitGuid());
				jsonDataMap.put("infectionInfo", infectionInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String infectionInfoJson = JsonUtil.objectToJson(infectionInfo);
		model.addAttribute("infectionInfoJson", infectionInfoJson);
		model.addAttribute("infectionInfo", (Map<String, Object>) jsonMap.get("infectionInfo"));

		Map<String, List<Map<String, Object>>> baseInfo = baseInfoService.getBaseInfoOfHomePageInfection();
		String baseInfoJson = JsonUtil.objectToJson(baseInfo);
		model.addAttribute("baseInfoJson", baseInfoJson);
		model.addAttribute("visitGuid", infectionInfo.getVisitGuid());

		return "medical_record/home_page/edit_infection_info";
	}

	@GetMapping("/edit_home_page_examination_reports_form")
	public String editHomePageExaminationReportsForm(String visitGuid, String fileName, Model model) {
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		Map<String, Object> map = medicalRecordService.getHospitalizationNoteByFirstGuid(visitGuid);
		
		if (null != map) {
			model.addAttribute("mrId", map.get("mr_id"));
			model.addAttribute("visitNumber", map.get("visit_number"));
		}

		if (StringUtils.isNotEmpty(fileName)) {
			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {
			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}

		Map<String, Object> examinationReportsInfo = (Map<String, Object>) jsonMap.get("examinationReportsInfo");
		if (examinationReportsInfo == null) {
			examinationReportsInfo = new HashMap<String, Object>();
		}
		String examinationReportsInfoJson = JsonUtil.objectToJson(examinationReportsInfo);
		model.addAttribute("examinationReportsInfoJson", examinationReportsInfoJson);
		model.addAttribute("examinationReportsInfo", examinationReportsInfo);
		
		return "medical_record/home_page/edit_examination_reports_info";
	}

	@ResponseBody
	@GetMapping("/getProgressNote")
	public Result getProgressNote(String visitGuid, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		List<String> progressNoteList = new ArrayList<String>();
		String progressNote = null;
		
		try {
			String jsonStr = hospNoteBasicJsonService.getHospBasicJsonByFirstGuid("\""+visitGuid+"\"");
			
			if (StringUtils.isNotBlank(jsonStr)) {
				Map jsonMap = JsonUtils.jsonToPojo(jsonStr, Map.class);
				Map progressNoteMap = jsonMap.get("progressNote")!=null?(Map)jsonMap.get("progressNote"):null;
				
				if (null != progressNoteMap) {
					List progressList = progressNoteMap.get("progressList")!=null?(List)progressNoteMap.get("progressList"):null;
				
					if (null != progressList && progressList.size() > 0) {
						String progressNoteDirectory = myConfig.getProgressNoteDir() + visitGuid;
					
						for(int i = 0; i < progressList.size(); i++) {
							String currentFilePath = progressNoteDirectory  +File.separator + progressList.get(i);
							String realFilePath = DiskManageUtil.getFileRealPath(config.getConfigFileStorageAllDisk(), currentFilePath);
							
							if (StringUtils.isBlank(realFilePath)) {
								log.error("在{}磁盘中找不到病程html文件,fileName={}, visitGuid={}", config.getConfigFileStorageAllDisk(),
										currentFilePath, visitGuid);
								continue;
							}
							
							File file = new File(realFilePath);
							String content= com.hutao.manage.util.IOUtils.readFile(file);
							
							if(StringUtils.isNotBlank(content)){
								content=content.replaceAll("nbsp", "ensp");
							}
							
							progressNoteList.add(content);
						}
					}
					
				} //end
				
			}
			
			return new Result(true, "读取html成功!", progressNoteList);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "系统异常!");
		}

	}

	@GetMapping("/edit_home_page_visit_progress_note_form")
	public String edit_home_page_visit_progress_note_form(String visitGuid, Model model, HttpServletResponse reponse) {
		Map<String, Object> map = medicalRecordService.getHospitalizationNoteByFirstGuid(visitGuid);
		
		if (null != map) {
			model.addAttribute("mrId", map.get("mr_id"));
			model.addAttribute("visitNumber", map.get("visit_number"));
		}
		
		model.addAttribute("firstGuid", visitGuid);
		
		return "medical_record/home_page/edit_progress_note";
	}

	
	@GetMapping("/edit_home_page_note_form")
	public String edit_home_page_note_form(String visitGuid,Model model,HttpServletResponse reponse){
		model.addAttribute("firstGuid", visitGuid);
		return "medical_record/home_page/edit_note_form";
	}
	

	@GetMapping("/search_home_page_visit_progress_note_form")
	public String search_home_page_visit_progress_note_form(String visitGuid, Model model,
			HttpServletResponse reponse) {

		model.addAttribute("firstGuid", visitGuid);
		return "medical_record/search_page/edit_progress_note";
	}

	/**
	 * 查看检验报告
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageExaminationReportsForm")
	public String searchHomePageExaminationReportsForm(String visitGuid, String fileName, Model model) {
		model.addAttribute("visitGuid", visitGuid);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> examinationReportsInfo = (Map<String, Object>) jsonMap.get("examinationReportsInfo");
		if (examinationReportsInfo == null) {
			examinationReportsInfo = new HashMap<String, Object>();
		}
		String examinationReportsInfoJson = JsonUtil.objectToJson(examinationReportsInfo);
		model.addAttribute("examinationReportsInfoJson", examinationReportsInfoJson);
		model.addAttribute("examinationReportsInfo", examinationReportsInfo);
		return "medical_record/search_page/edit_examination_reports_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_examination_reports")
	public String editHomePageExaminationReports(HospitalVisitExaminationReportsInfo examinationReportsInfo,
			HttpServletRequest request, Model model) {
		model.addAttribute("visitGuid", examinationReportsInfo.getVisitGuid());
		String filePath = myConfig.getHospitalVisitJsonPath()
				+ StringUtil.getLocalPath(examinationReportsInfo.getVisitGuid());
		String fileName = examinationReportsInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + examinationReportsInfo.getVisitGuid()
				+ "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, examinationReportsInfo.getVisitGuid());
			return "medical_record/home_page/edit_examination_reports_info";
		}
		
		String realFilePath = diskName + filePath.trim().substring(1);
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		examinationReportsInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("examinationReportsInfo", examinationReportsInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(examinationReportsInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(examinationReportsInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
		
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("examinationReportsInfo", examinationReportsInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(examinationReportsInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", examinationReportsInfo.getVisitGuid());
				jsonDataMap.put("examinationReportsInfo", examinationReportsInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String examinationReportsInfoJson = JsonUtil.objectToJson(examinationReportsInfo);
		model.addAttribute("examinationReportsInfoJson", examinationReportsInfoJson);
		model.addAttribute("examinationReportsInfo", (Map<String, Object>) jsonMap.get("examinationReportsInfo"));

		return "medical_record/home_page/edit_examination_reports_info";
	}

	@GetMapping("/edit_home_page_doctor_advice_temporary_form")
	public String editHomePageDoctorAdviceTemporaryForm(String visitGuid, Model model) {
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		
		Map<String, Object> doctorAdviceTemporaryInfo = (Map<String, Object>) jsonMap.get("doctorAdviceTemporaryInfo");
		
		if (doctorAdviceTemporaryInfo == null) {
			doctorAdviceTemporaryInfo = new HashMap<String, Object>();
		}
		
		String doctorAdviceTemporaryInfoJson = JsonUtil.objectToJson(doctorAdviceTemporaryInfo);
		model.addAttribute("doctorAdviceTemporaryInfoJson", doctorAdviceTemporaryInfoJson);
		model.addAttribute("doctorAdviceTemporaryInfo", doctorAdviceTemporaryInfo);
		
		return "medical_record/home_page/edit_doctor_advice_temporary_info";
	}

	/**
	 * 查看临时医嘱
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageDoctorAdviceTemporaryForm")
	public String searchHomePageDoctorAdviceTemporaryForm(String visitGuid, String fileName, Model model) {
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();

		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> doctorAdviceTemporaryInfo = (Map<String, Object>) jsonMap.get("doctorAdviceTemporaryInfo");
		if (doctorAdviceTemporaryInfo == null) {
			doctorAdviceTemporaryInfo = new HashMap<String, Object>();
		}
		String doctorAdviceTemporaryInfoJson = JsonUtil.objectToJson(doctorAdviceTemporaryInfo);
		model.addAttribute("doctorAdviceTemporaryInfoJson", doctorAdviceTemporaryInfoJson);
		model.addAttribute("doctorAdviceTemporaryInfo", doctorAdviceTemporaryInfo);
		return "medical_record/search_page/edit_doctor_advice_temporary_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_doctor_advice_temporary")
	public String editHomePageDoctorAdviceTemporary(HospitalVisitDoctorAdviceTemporaryInfo doctorAdviceTemporaryInfo,
			HttpServletRequest request, Model model) {
		model.addAttribute("visitGuid", doctorAdviceTemporaryInfo.getVisitGuid());

		String filePath = myConfig.getHospitalVisitJsonPath()
				+ StringUtil.getLocalPath(doctorAdviceTemporaryInfo.getVisitGuid());
		String fileName = doctorAdviceTemporaryInfo.getVisitGuid() + ".json";
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + doctorAdviceTemporaryInfo.getVisitGuid()
				+ "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, doctorAdviceTemporaryInfo.getVisitGuid());
			return "medical_record/home_page/edit_doctor_advice_temporary_info";
		}
		
		String realFilePath = diskName + filePath.trim().substring(1);
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		doctorAdviceTemporaryInfo.clearEmpty();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("doctorAdviceTemporaryInfo", doctorAdviceTemporaryInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		
		try {
		
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);			

			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(doctorAdviceTemporaryInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(doctorAdviceTemporaryInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("doctorAdviceTemporaryInfo", doctorAdviceTemporaryInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(doctorAdviceTemporaryInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", doctorAdviceTemporaryInfo.getVisitGuid());
				jsonDataMap.put("doctorAdviceTemporaryInfo", doctorAdviceTemporaryInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String doctorAdviceTemporaryInfoJson = JsonUtil.objectToJson(doctorAdviceTemporaryInfo);
		model.addAttribute("doctorAdviceTemporaryInfoJson", doctorAdviceTemporaryInfoJson);
		model.addAttribute("doctorAdviceTemporaryInfo", (Map<String, Object>) jsonMap.get("doctorAdviceTemporaryInfo"));

		return "medical_record/home_page/edit_doctor_advice_temporary_info";
	}

	@GetMapping("/edit_home_page_doctor_advice_standing_form")
	public String editHomePageDoctorAdviceStandingForm(String visitGuid, Model model) {
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		
		Map<String, Object> doctorAdviceStandingInfo = (Map<String, Object>) jsonMap.get("doctorAdviceStandingInfo");
		
		if (doctorAdviceStandingInfo == null) {
			doctorAdviceStandingInfo = new HashMap<String, Object>();
		}
		
		String doctorAdviceStandingInfoJson = JsonUtil.objectToJson(doctorAdviceStandingInfo);
		model.addAttribute("doctorAdviceStandingInfoJson", doctorAdviceStandingInfoJson);
		model.addAttribute("doctorAdviceStandingInfo", doctorAdviceStandingInfo);
		
		return "medical_record/home_page/edit_doctor_advice_standing_info";
	}

	/**
	 * 查看长期医嘱
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageDoctorAdviceStandingForm")
	public String searchHomePageDoctorAdviceStandingForm(String visitGuid, String fileName, Model model) {
		model.addAttribute("visitGuid", visitGuid);

		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> doctorAdviceStandingInfo = (Map<String, Object>) jsonMap.get("doctorAdviceStandingInfo");
		if (doctorAdviceStandingInfo == null) {
			doctorAdviceStandingInfo = new HashMap<String, Object>();
		}
		String doctorAdviceStandingInfoJson = JsonUtil.objectToJson(doctorAdviceStandingInfo);
		model.addAttribute("doctorAdviceStandingInfoJson", doctorAdviceStandingInfoJson);
		model.addAttribute("doctorAdviceStandingInfo", doctorAdviceStandingInfo);
		return "medical_record/search_page/edit_doctor_advice_standing_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_doctor_advice_standing")
	public String editHomePageDoctorAdviceStanding(HospitalVisitDoctorAdviceStandingInfo doctorAdviceStandingInfo,
			Model model, HttpServletRequest request) {
		model.addAttribute("visitGuid", doctorAdviceStandingInfo.getVisitGuid());
		doctorAdviceStandingInfo.clearEmpty();
		String filePath = myConfig.getHospitalVisitJsonPath()
				+ StringUtil.getLocalPath(doctorAdviceStandingInfo.getVisitGuid());
		String fileName = doctorAdviceStandingInfo.getVisitGuid() + ".json";
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + doctorAdviceStandingInfo.getVisitGuid()
				+ "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, doctorAdviceStandingInfo.getVisitGuid());
			return "medical_record/home_page/edit_doctor_advice_standing_info";
		} 
		
		String realFilePath = diskName + filePath.trim().substring(1);
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		jsonMap.put("doctorAdviceStandingInfo", doctorAdviceStandingInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(doctorAdviceStandingInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(doctorAdviceStandingInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("doctorAdviceStandingInfo", doctorAdviceStandingInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(doctorAdviceStandingInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", doctorAdviceStandingInfo.getVisitGuid());
				jsonDataMap.put("doctorAdviceStandingInfo", doctorAdviceStandingInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		String doctorAdviceStandingInfoJson = JsonUtil.objectToJson(doctorAdviceStandingInfo);
		model.addAttribute("doctorAdviceStandingInfoJson", doctorAdviceStandingInfoJson);
		model.addAttribute("doctorAdviceStandingInfo", (Map<String, Object>) jsonMap.get("doctorAdviceStandingInfo"));

		return "medical_record/home_page/edit_doctor_advice_standing_info";
	}

	@GetMapping("/edit_home_page_visit_cost_form")
	public String editHomePageVisitCostForm(String visitGuid, Model model) {
		model.addAttribute("visitGuid", visitGuid);
		
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		String hospitalVisitDataJson = hospNoteBasicJsonService
				.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
		
		if (hospitalVisitDataJson != null) {
			jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
		}
		
		Map<String, Object> visitCostInfo = (Map<String, Object>) jsonMap.get("visitCostInfo");
		
		if (visitCostInfo == null) {
			visitCostInfo = new HashMap<String, Object>();
		}
		
		String visitCostInfoJson = JsonUtil.objectToJson(visitCostInfo);
		model.addAttribute("visitCostInfoJson", visitCostInfoJson);
		model.addAttribute("visitCostInfo", visitCostInfo);
		
		return "medical_record/home_page/edit_visit_cost_info";
	}

	/**
	 * 查看住院费用
	 * 
	 * @param visitGuid
	 * @param model
	 * @return
	 */
	@GetMapping("/searchHomePageVisitCostForm")
	public String searchHomePageVisitCostForm(String visitGuid, String fileName, Model model) {
		model.addAttribute("visitGuid", visitGuid);

		// String filePath = myConfig.getHospitalVisitJsonPath() +
		// StringUtil.getLocalPath(visitGuid);
		// String fileName = visitGuid + ".json";
		// Map<String, Object> jsonMap = readLineFile(filePath, fileName);
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(fileName)) {

			String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitGuid + "/";
			String versionFileName = fileName;
			jsonMap = readLineFile(versionFilePath, versionFileName);
		} else {

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));
			if (hospitalVisitDataJson != null) {
				jsonMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
			}
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> visitCostInfo = (Map<String, Object>) jsonMap.get("visitCostInfo");
		if (visitCostInfo == null) {
			visitCostInfo = new HashMap<String, Object>();
		}
		String visitCostInfoJson = JsonUtil.objectToJson(visitCostInfo);
		model.addAttribute("visitCostInfoJson", visitCostInfoJson);
		model.addAttribute("visitCostInfo", visitCostInfo);
		return "medical_record/search_page/edit_visit_cost_info";
	}

	@SuppressWarnings("unchecked")
	@PostMapping("/edit_home_page_visit_cost")
	public String editHomePageVisitCost(HospitalVisitCostInfo visitCostInfo, HttpServletRequest request, Model model) {

		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(visitCostInfo.getVisitGuid());
		String fileName = visitCostInfo.getVisitGuid() + ".json";

		String versionFilePath = myConfig.getHospitalVisitJsonVersionPath() + visitCostInfo.getVisitGuid() + "/";
		// 版本文件名称
		String versionFileName = DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";

		String diskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), filePath + fileName);
		
		if (StringUtils.isBlank(diskName)) {
			log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", config.getConfigFileStorageAllDisk(), 
					filePath + fileName, visitCostInfo.getVisitGuid());
			return "medical_record/home_page/edit_visit_cost_info";
		} 
		
		String realFilePath = diskName + filePath.trim().substring(1);
		Map<String, Object> jsonMap = readLineFile(realFilePath, fileName);
		
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		jsonMap.put("userId", currentUser);
		jsonMap.put("visitCostInfo", visitCostInfo);
		String jsonMapJson = JsonUtil.objectToJson(jsonMap);
		try {
			FileUtil.createOrEditFile(jsonMapJson, realFilePath, fileName);
			//本地json版本文件
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			
			HospNoteVersion hospNoteVersion = new HospNoteVersion();
			hospNoteVersion.setCreateTime(new Date());
			hospNoteVersion.setFirstGuid(visitCostInfo.getVisitGuid());
			hospNoteVersion.setFileName(versionFileName);
			hospNoteVersion.setOperator(currentUser);
			hospitalNoteVersionService.insertHospitalNoteVersion(hospNoteVersion);

			String hospitalVisitDataJson = hospNoteBasicJsonService
					.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitCostInfo.getVisitGuid()));
			Map<String, Object> jsonDataMap = new HashMap<String, Object>();
			if (hospitalVisitDataJson != null) {
				jsonDataMap = JsonUtils.jsonToPojo(hospitalVisitDataJson, Map.class);
				jsonDataMap.put("visitCostInfo", visitCostInfo);
				hospNoteBasicJsonService.updateHospBasicJsonByFirstGuid(visitCostInfo.getVisitGuid(),
						JsonUtils.objectToJson(jsonDataMap));
			} else {
				jsonDataMap.put("firstGuid", visitCostInfo.getVisitGuid());
				jsonDataMap.put("visitCostInfo", visitCostInfo);
				hospNoteBasicJsonService.addHospNoteBasicJson(JsonUtils.objectToJson(jsonDataMap));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonMap = JsonUtil.jsonToPojo(jsonMapJson, Map.class);

		model.addAttribute("visitGuid", visitCostInfo.getVisitGuid());
		model.addAttribute("visitCostInfo", (Map<String, Object>) jsonMap.get("visitCostInfo"));
		model.addAttribute("visitCostInfoJson", JsonUtil.objectToJson(visitCostInfo));
		return "medical_record/home_page/edit_visit_cost_info";
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> readLineFile(String filePath, String fileName) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		try {
			File destFile = new File(filePath, fileName);
			String jsonStr = null;
			if (destFile.exists()) {
				// FileReader fr = new FileReader(destFile);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(new FileInputStream(filePath + fileName), "UTF-8"));
				jsonStr = br.readLine();
				jsonMap = JsonUtil.jsonToPojo(jsonStr, Map.class);

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return jsonMap;
	}

	@SuppressWarnings("unchecked")
	public String readHtmlFile(String filePath, String fileName) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		String jsonStr = null;
		try {
			File destFile = new File(filePath, fileName);
			if (destFile.exists()) {
				// FileReader fr = new FileReader(destFile);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(new FileInputStream(filePath + fileName), "UTF-8"));
				jsonStr = br.readLine();

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return jsonStr;
	}

	@GetMapping("/print1")
	public String homePagePrint1(String visitGuid, String applyName, Model model, HttpServletRequest request) {
		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(visitGuid);
		String fileName = visitGuid + ".json";
		Map<String, Object> jsonMap = readLineFile(filePath, fileName);

		String hospitalVisitHomePageJson = JsonUtil.objectToJson(jsonMap);

		model.addAttribute("hospitalVisitJson", JsonUtils.objectToJson(hospitalVisitHomePageJson));

		if (StringUtils.isNotEmpty(applyName)) {
			try {
				applyName = URLDecoder.decode(applyName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else {
			applyName = CookieUtils.getCookieValue(request, "userName");
		}

		// 病案图片
		List<Map<String, Object>> scanFiles = scanFileService.getPaginationScanFilesByFirstGuid(visitGuid);
		// String applyName = CookieUtils.getCookieValue(request, "userName");

		/*if (MapUtils.isNotEmpty(jsonMap)) {
			Map<String, Object> recordSheeMap = (Map<String, Object>) jsonMap.get("recordSheet");
			List<String> recordFileNameList = getOtherRecordFileNameList(recordSheeMap,visitGuid);
			if(CollectionUtils.isNotEmpty(recordFileNameList)){
				List<Map<String,Object>> mapList = appendScanFile(recordFileNameList);
				if(CollectionUtils.isNotEmpty(mapList)){
					scanFiles.addAll(mapList);
				}
			}
		}*/

		List<PrintPageDTO> scanFileSortList = new ArrayList<>();
		
		if (CollectionUtils.isNotEmpty(scanFiles)) {
			PrintPageDTO printPageDTO= null;
			for (Map<String, Object> scanFil : scanFiles) {
				printPageDTO= new PrintPageDTO();
				printPageDTO.setMrPageTypeId(scanFil.get("mr_page_type_id")==null?100:(Integer)scanFil.get("mr_page_type_id"));
				String fileName1 = scanFil.get("fileName") == null ? "" : (String) scanFil.get("fileName");
				String fileUrl = scanFil.get("fileUrl") == null ? "" : (String) scanFil.get("fileUrl");
				String fileHash = scanFil.get("fileHash") == null ? "" : (String) scanFil.get("fileHash");
				String originalFileName = scanFil.get("originalFileName") == null ? "" : (String) scanFil.get("originalFileName");
				int len = originalFileName.indexOf(".");
				String originalName = originalFileName.substring(0,len);
				String secret = MD5.md5(applyName + fileHash);
				printPageDTO.setOriginalFileName(originalName);

				// 调用sso生成图片水印
//				Map<String, String> cachePicParam = new HashMap<>();
//				cachePicParam.put("fileName", fileUrl + fileName1);
//				cachePicParam.put("secret", secret);
//				try {
//					String preWatermark = conf.getWaterMarkPre();
//
//					String signature = URLEncoder.encode(preWatermark + "--" + applyName, "utf-8");
//					cachePicParam.put("signature", signature);
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				}
//				String cachePicJson = HttpClientUtil.doPost(conf.getSeekMarkPicUrl(), cachePicParam);
//				if (StringUtils.isNotEmpty(cachePicJson)) {
//					Result result = JsonUtils.jsonToPojo(cachePicJson, Result.class);
//					if (result.isSuccess()) {
//						scanFil.put("markPicUrl", result.getData());
//						printPageDTO.setMarkPicUrl((String)result.getData());
//						
//						scanFileSortList.add(printPageDTO);
//					}
//				}
				
				printPageDTO.setMarkPicUrl(conf.getHospitalizationNoteResourceUrl()+fileUrl+fileName1);
				scanFileSortList.add(printPageDTO);
			}
			
	
			
			Collections.sort(scanFileSortList,new PrintPageDTO());
			
			
		}
		model.addAttribute("firstGuid", visitGuid);
		model.addAttribute("scanFiles", scanFileSortList);
		model.addAttribute("hospitalName", conf.getWaterMarkPre());
		model.addAttribute("applyName", applyName);

		return "medical_record/home_page/print";
		
		
		
	}
	
	@GetMapping("/print")
	public String homePagePrint(String visitGuid, String applyName, Model model, HttpServletRequest request) {
		/*String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(visitGuid);
		String fileName = visitGuid + ".json";
		Map<String, Object> jsonMap = readLineFile(filePath, fileName);

		String hospitalVisitHomePageJson = JsonUtil.objectToJson(jsonMap);

		model.addAttribute("hospitalVisitJson", JsonUtils.objectToJson(hospitalVisitHomePageJson));*/

		if (StringUtils.isNotEmpty(applyName)) {
			try {
				applyName = URLDecoder.decode(applyName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else {
			applyName = CookieUtils.getCookieValue(request, "userName");
		}

		// 病案图片
		List<MedicalRecordPrinterImage> scanFiles = medRecordService.getPreviewMedicalRecordImages(visitGuid);
		// String applyName = CookieUtils.getCookieValue(request, "userName");

		/*if (MapUtils.isNotEmpty(jsonMap)) {
			Map<String, Object> recordSheeMap = (Map<String, Object>) jsonMap.get("recordSheet");
			List<String> recordFileNameList = getOtherRecordFileNameList(recordSheeMap,visitGuid);
			if(CollectionUtils.isNotEmpty(recordFileNameList)){
				List<Map<String,Object>> mapList = appendScanFile(recordFileNameList);
				if(CollectionUtils.isNotEmpty(mapList)){
					scanFiles.addAll(mapList);
				}
			}
		}*/

		model.addAttribute("firstGuid", visitGuid);
		model.addAttribute("scanFiles", scanFiles);
		model.addAttribute("hospitalName", conf.getWaterMarkPre());
		model.addAttribute("applyName", applyName);

		return "medical_record/home_page/print";
		
		
		
	}
	@Autowired
	private Config config;
	
	@GetMapping("/medical_record_image_to_pdf")
	public String medicalRecordImageToPDF(String visitGuid) {
		/*String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(visitGuid);
		String fileName = visitGuid + ".json";
		Map<String, Object> jsonMap = readLineFile(filePath, fileName);

		String hospitalVisitHomePageJson = JsonUtil.objectToJson(jsonMap);

		model.addAttribute("hospitalVisitJson", JsonUtils.objectToJson(hospitalVisitHomePageJson));*/

		// 病案图片
		List<MedicalRecordPrinterImage> scanFiles = medRecordService.getPreviewMedicalRecordImages(visitGuid);
		List<String> imagePaths = new ArrayList<String>();
		for (MedicalRecordPrinterImage medicalRecordPrinterImage : scanFiles) {
			imagePaths.add(medicalRecordPrinterImage.getImageUrl());
		}
		
		String pdfPath = config.getUploadResourcePath()+"temp/"+visitGuid+".pdf";
		try {
			PDFUtil.createPDFByImagePaths(imagePaths, pdfPath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String pdfUrl = conf.getHospitalizationNoteResourceUrl()+"temp/"+visitGuid+".pdf";
		return "redirect:"+pdfUrl;
		
	}
	
	
	
	public  List<Map<String,Object>> appendScanFile(List<String> recordFileNameList){
		List<Map<String,Object>> mapList = new ArrayList<>();
		for (String recordFileName : recordFileNameList) {
			Map<String,Object> map = new HashMap<>();
			int length=recordFileName.lastIndexOf("/");
			int hostServerLength=conf.getUploadResourcePath().length();
			String fileName=recordFileName.substring(length+1, recordFileName.length());
			String fileHash=recordFileName.substring(hostServerLength,length+1);
			String fileUrl = recordFileName.substring(hostServerLength,length+1);
			if( recordFileName.contains("smtzgc") ){
				map.put("mr_page_type_id", 48);
			}else if(recordFileName.contains("xuetcd")){
				map.put("mr_page_type_id",30);
			/*else if(recordFileName.contains("yibanhj")){
				map.put("mr_page_type_id", 26);
			}else if(recordFileName.contains("bingzhj") || recordFileName.contains("bingwhj")){
				map.put("mr_page_type_id", 27);*/
			}else if(recordFileName.contains("tebiehj")){
				map.put("mr_page_type_id", 28);
			}
			map.put("fileName", fileName);
			map.put("fileHash", fileHash);
			map.put("fileUrl", fileUrl);
			mapList.add(map);
			
		}
		return mapList;
	}

	public List<String> getOtherRecordFileNameList(Map<String, Object> recordSheeMap, String visitGuid			) {
		List<String> recordFileNameList = new ArrayList<>();
		try {
			if (MapUtils.isEmpty(recordSheeMap)) {
				return recordFileNameList;
			}
			Map<String, Object> temperatureRecord = (Map<String, Object>) recordSheeMap.get("temperatureRecord");
			if (MapUtils.isNotEmpty(temperatureRecord)) {
				List<String> imageFilePathList = (List<String>) temperatureRecord.get("imageFilePathList");
				if (CollectionUtils.isNotEmpty(imageFilePathList)) {
					for (String filePathName : imageFilePathList) {

						recordFileNameList.add(conf.getUploadResourcePath()+ "CMIS/tiwen/"
								+ visitGuid + "/" + filePathName);
					}
				}
			}

			Map<String, Object> electrocardiogramRecord = (Map<String, Object>) recordSheeMap
					.get("electrocardiogramRecord");
			if (MapUtils.isNotEmpty(electrocardiogramRecord)) {
				List<String> imageFilePathList = (List<String>) electrocardiogramRecord.get("imageFilePathList");
				if (CollectionUtils.isNotEmpty(imageFilePathList)) {
					for (String filePathName : imageFilePathList) {

						recordFileNameList.add(conf.getUploadResourcePath() + "CMIS/xindjc/"
								+ visitGuid + "/" + filePathName);
					}
				}
			}

			Map<String, Object> vitalSignRecord = (Map<String, Object>) recordSheeMap.get("vitalSignRecord");
			if (MapUtils.isNotEmpty(vitalSignRecord)) {
				List<String> imageFilePathList = (List<String>) vitalSignRecord.get("imageFilePathList");
				if (CollectionUtils.isNotEmpty(imageFilePathList)) {
					for (String filePathName : imageFilePathList) {

						recordFileNameList.add(conf.getUploadResourcePath() + "CMIS/smtzgc/"
								+ visitGuid + "/" + filePathName);
					}
				}
			}

			Map<String, Object> bloodSugarRecord = (Map<String, Object>) recordSheeMap.get("bloodSugarRecord");
			if (MapUtils.isNotEmpty(bloodSugarRecord)) {
				List<String> imageFilePathList = (List<String>) bloodSugarRecord.get("imageFilePathList");
				if (CollectionUtils.isNotEmpty(imageFilePathList)) {
					for (String filePathName : imageFilePathList) {

						recordFileNameList.add(conf.getUploadResourcePath() + "CMIS/xuetcd/"
								+ visitGuid + "/" + filePathName);
					}
				}
			}
			
			Map<String, Object> nurseRecord = (Map<String, Object>) recordSheeMap.get("nurseRecord");
			if (MapUtils.isNotEmpty(nurseRecord)) {
				Map<String, Object> illNurseRecord = (Map<String, Object>) nurseRecord.get("IllNurseRecord");
				if (MapUtils.isNotEmpty(illNurseRecord)) {
					List<String> filePathNameList = (List<String>) illNurseRecord.get("imageFilePathList");
					if (CollectionUtils.isNotEmpty(filePathNameList)) {
						for (String filePathName : filePathNameList) {
							recordFileNameList.add(conf.getUploadResourcePath()+ "CMIS/bingzhj/"
									+ visitGuid + "/" + filePathName);
						}
					}
				}

				Map<String, Object> specialNurseRecord = (Map<String, Object>) nurseRecord.get("specialNurseRecord");
				if (MapUtils.isNotEmpty(specialNurseRecord)) {
					List<String> filePathNameList = (List<String>) specialNurseRecord.get("imageFilePathList");
					if (CollectionUtils.isNotEmpty(filePathNameList)) {
						for (String filePathName : filePathNameList) {
							recordFileNameList.add(conf.getUploadResourcePath() + "CMIS/tebiehj/"
									+ visitGuid + "/" + filePathName);
						}
					}
				}

				Map<String, Object> criticalCareRecord = (Map<String, Object>) nurseRecord.get("criticalCareRecord");
				if (MapUtils.isNotEmpty(criticalCareRecord)) {
					List<String> filePathNameList = (List<String>) criticalCareRecord.get("imageFilePathList");
					if (CollectionUtils.isNotEmpty(filePathNameList)) {
						for (String filePathName : filePathNameList) {
							recordFileNameList.add(conf.getUploadResourcePath()+ "CMIS/bingwhj/"
									+ visitGuid + "/" + filePathName);
						}
					}
				}

				Map<String, Object> generalNurseRecord = (Map<String, Object>) nurseRecord.get("generalNurseRecord");
				if (MapUtils.isNotEmpty(generalNurseRecord)) {
					List<String> filePathNameList = (List<String>) generalNurseRecord.get("imageFilePathList");
					if (CollectionUtils.isNotEmpty(filePathNameList)) {
						for (String filePathName : filePathNameList) {
							recordFileNameList.add(conf.getUploadResourcePath() + "CMIS/yibanhj/"
									+ visitGuid + "/" + filePathName);
						}
					}
				}
				
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return recordFileNameList;
	}

	@PostMapping("/homePageTreamtTrace")
	public String homePageTreamtTrace(String visitGuid, Model model, HttpServletRequest request) {
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		treatmentTraceService.addTreatmentTraceHomePage(visitGuid, currentUser);
		return "redirect:/medical_record/edit_home_page_index_form?=" + visitGuid;
	}

	@GetMapping("/ajaxMedicalRecordDataByVisitGuid")
	@ResponseBody
	public String ajaxMedicalRecordDataByVisitGuid(String visitGuid, HttpServletResponse response, Model model) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		RespondResult respondResult = null;
		try {
			String data = hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(visitGuid));

			if (data != null) {

				respondResult = new RespondResult(true, "500", "成功", data);
			} else {
				respondResult = new RespondResult(true, "404", "资源不存在", "");
			}
		} catch (Exception ex) {
			respondResult = new RespondResult(false, "500", ex.getMessage(), "");
		}

		return JsonUtil.objectToJson(respondResult);
	}
	
	
	//获取护理记录
	@GetMapping("/ajaxPdfPigeonhole")
	@ResponseBody
	public Result ajaxPdfPigeonhole(String firstGuid ,Integer typeId, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<>();
		
		try {
			String typeName = PdfPigeonholeEnum.valueOf(typeId).getDesc();
			String data = hospNoteBasicJsonService.getHospBasicJsonByFirstGuid(StringUtil.handleJsonParam(firstGuid));
			map.put("jsonStr", data);
			map.put("imgUrl",  pdfPigeonholeDir + File.separator + typeName + File.separator + firstGuid + File.separator);
			List imgList = new ArrayList();
			
			Map jsonMap = JsonUtils.jsonToPojo(data, Map.class);
			if (null != jsonMap) {
				Map recordSheetMap = (Map)jsonMap.get("recordSheet");
				if (null != recordSheetMap) {
					if (typeId == 1) { //temperatureRecord
						Map temperatureRecordMap = (Map)recordSheetMap.get("temperatureRecord");
						if (null != temperatureRecordMap) {
						  List imagePathList = (List)temperatureRecordMap.get("imageFilePathList");
						  
						  if (null != imagePathList && imagePathList.size() > 0) {
							  for (Object imagePath : imagePathList) {
								  getNurseImageUrl(typeName, firstGuid, imagePath, imgList);
								 
							  }
						  } // end
						}
					} else if (typeId == 2) { //bloodSugarRecord
						Map temperatureRecordMap = (Map)recordSheetMap.get("bloodSugarRecord");
						if (null != temperatureRecordMap) {
						  List imagePathList = (List)temperatureRecordMap.get("imageFilePathList");
						  if (null != imagePathList && imagePathList.size() > 0) {
							  for (Object imagePath : imagePathList) {
								  getNurseImageUrl(typeName, firstGuid, imagePath, imgList);
							  }
						  }
						}
					} else if (typeId == 3) { //electrocardiogramRecord
						Map temperatureRecordMap = (Map)recordSheetMap.get("electrocardiogramRecord");
						if (null != temperatureRecordMap) {
						  List imagePathList = (List)temperatureRecordMap.get("imageFilePathList");
						  if (null != imagePathList && imagePathList.size() > 0) {
							  for (Object imagePath : imagePathList) {
								  getNurseImageUrl(typeName, firstGuid, imagePath, imgList);
							  }
						  }
						}
					} else if (typeId == 4) { //vitalSignRecord
						Map temperatureRecordMap = (Map)recordSheetMap.get("vitalSignRecord");
						if (null != temperatureRecordMap) {
						  List imagePathList = (List)temperatureRecordMap.get("imageFilePathList");
						  if (null != imagePathList && imagePathList.size() > 0) {
							  for (Object imagePath : imagePathList) {
								  getNurseImageUrl(typeName, firstGuid, imagePath, imgList);
							  }
						  }
						}
					} else if (typeId == 5) { //nurseRecord IllNurseRecord
						Map nurseRecordMap = (Map)recordSheetMap.get("nurseRecord");
						Map temperatureRecordMap = (Map)nurseRecordMap.get("IllNurseRecord");
						if (null != temperatureRecordMap) {
						  List imagePathList = (List)temperatureRecordMap.get("imageFilePathList");
						  if (null != imagePathList && imagePathList.size() > 0) {
							  for (Object imagePath : imagePathList) {
								  getNurseImageUrl(typeName, firstGuid, imagePath, imgList);
							  }
						  }
						}
					} else if (typeId == 6) {//nurseRecord specialNurseRecord
						Map nurseRecordMap = (Map)recordSheetMap.get("nurseRecord");
						Map temperatureRecordMap = (Map)nurseRecordMap.get("specialNurseRecord");
						if (null != temperatureRecordMap) {
						  List imagePathList = (List)temperatureRecordMap.get("imageFilePathList");
						  if (null != imagePathList && imagePathList.size() > 0) {
							  for (Object imagePath : imagePathList) {
								  getNurseImageUrl(typeName, firstGuid, imagePath, imgList);
							  }
						  }
						}
					} else if (typeId == 7) {//nurseRecord criticalCareRecord
						Map nurseRecordMap = (Map)recordSheetMap.get("nurseRecord");
						Map temperatureRecordMap = (Map)nurseRecordMap.get("criticalCareRecord");
						if (null != temperatureRecordMap) {
						  List imagePathList = (List)temperatureRecordMap.get("imageFilePathList");
						  if (null != imagePathList && imagePathList.size() > 0) {
							  for (Object imagePath : imagePathList) {
								  getNurseImageUrl(typeName, firstGuid, imagePath, imgList);
							  }
						  }
						}
					} else if (typeId == 8) {//nurseRecord generalNurseRecord
						Map nurseRecordMap = (Map)recordSheetMap.get("nurseRecord");
						Map temperatureRecordMap = (Map)nurseRecordMap.get("generalNurseRecord");
						if (null != temperatureRecordMap) {
						  List imagePathList = (List)temperatureRecordMap.get("imageFilePathList");
						  if (null != imagePathList && imagePathList.size() > 0) {
							  for (Object imagePath : imagePathList) {
								  getNurseImageUrl(typeName, firstGuid, imagePath, imgList);
							  }
						  }
						}
					}
				}
			}
			
			map.put("imgList", imgList);
			
			return new Result(true, "查询成功!", map);
		} catch (Exception e) {
			return new Result(false, "系统异常!");
		}
	}
	
	public void getNurseImageUrl(String typeName, String firstGuid, Object imagePath, List imgList) {
		  String currentFilePath = config.getUploadResourcePath()+"CMIS"+ File.separator + typeName + File.separator + firstGuid + File.separator+imagePath;
		  String currentFileUrl = pdfPigeonholeDir + File.separator + typeName + File.separator + firstGuid + File.separator + imagePath; 
		  String realDiskName = DiskManageUtil.getDiskNameByFileName(config.getConfigFileStorageAllDisk(), currentFilePath);
		  
		  if (StringUtils.isNotBlank(realDiskName)) {
			  imgList.add(currentFileUrl.replace("upload", "upload" + realDiskName.trim()));
		  }
	}
	
	
	
	
	
}


